关于Android中Service的手动、自动以及其在特殊条件下的重启

上一篇博客有说到Service之间的守护问题。

博客地址:http://blog.csdn.net/lemon_tree12138/article/details/40322887

接着这个Sevice的守护,我们可以做一些事。例如重启。看到重启你是不是就会想到Service自身来重启呢?很遗憾,Service不能在kill(ondestory)掉自己之后又重新onstart,所以我们要人为地为其进行重启,这里就要利用上一博客中的Service之间的守护问题了,其实都是很简单和比较常规的做法。下面从第一个手动重启开始。

1. 手动重启Service:

核心代码:

Intent killOneIntent = new Intent();
killOneIntent.setAction("com.example.servicedemo.ServiceTwo");
MainActivity.this.stopService(killOneIntent);
这里有Action需要在Manifest配置文件中添加,如下:

<service
            android:name="ServiceTwo"
            android:process=":remote" >
            <intent-filter>
                <action android:name="com.example.servicedemo.ServiceTwo" />
            </intent-filter>
        </service>

2. 自动重启Service:

核心代码:

Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                	// 每隔10秒重启一次当前Service
                	if ((System.currentTimeMillis() / 1000) % 10 == 0) {
						stopSelf();
					}
                	
                    boolean b = MainActivity.isServiceWorked(ServiceTwo.this, "com.example.servicedemo.ServiceOne");
                    if(!b) {
                        Intent service = new Intent(ServiceTwo.this, ServiceOne.class);
                        startService(service);
                    }
                }
            };
            timer.schedule(task, 0, 1000);
        }
    });
在这里我们做的重启条件是每10秒重启一次,所以我们需要开启一个线程来进行读秒,如果到了10秒,就“重启”。这里笔者做一件偷懒的事,对读秒的算法只是去获取系统时间,并对其取余,这样的结果就是在于最初的10秒可能不足,当然改善的方法有很多。笔者这里不作演示。

3. 特殊条件下的重启:

核心代码:

class ScreenBroadcastReceiver extends BroadcastReceiver {
    	
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String intentActionString = intent.getAction();
                if (intentActionString.equals(Intent.ACTION_SCREEN_ON)) { // 开屏
                	Log.e("screenon" + TAG, "----------------------- on!");
                } else if (intentActionString.equals(Intent.ACTION_SCREEN_OFF)) { // 锁屏
                	Log.e("screenon" + TAG, "----------------------- off!");
                	stopSelf();
                } else if (intentActionString.equals(Intent.ACTION_USER_PRESENT)) { // 解锁
                	Log.e("screenon" + TAG, "----------------------- unlock!");
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
这里用到的是监测屏幕开屏、关屏状态。(其实这里的方法和第二种自启是同一回事。)
如果没有看我上一篇博客,而且对Service的重启这一块不是很了解的朋友们,可能就会问一个题,这里的都对Service进行stop啊,没有restart,难道Service的stop就是restart,其实不是的。感兴趣的朋友可以看看我的上一博客《Android中利用服务来守护进程》。


工程连接:http://download.csdn.net/detail/u013761665/8129761

原文地址:https://www.cnblogs.com/fengju/p/6336135.html