现在的位置: 首页 > 综合 > 正文

Android Service 的重启

2013年10月01日 ⁄ 综合 ⁄ 共 1608字 ⁄ 字号 评论关闭

    做APP的时候,我们可能需要一个后台服务一直在运行着,得用到Service组件。

    但服务可能在如下情况被杀死:

    A.用户手动点击停止。

    B.采用第三方软件(比如360手机卫士)进行清理,当然这样子除了系统服务外,其他的进程肯定也会被杀死,除非跟手机厂商联系。

    这时候可能需要重启该服务,上网看了半天,有提到用Timer、AlarmManager去实现间歇性的发送广播启动Service(注册的广播接收后,启动Service),我实现了下,发现还是在B情况下还是不能满足。

    我手机上装了一个卡卡司机助手,发现在B情况下,杀掉后,服务过段时间自动启动了,观察Log打印。

   

07-12 14:12:15.735: I/HadesLee(1456): Receiver,action=android.intent.action.USER_PRESENT
07-12 14:12:15.745: I/HadesLee(1456): KakaService.onCreate....
07-12 14:12:15.745: I/HadesLee(1456): KakaService.onStartCommand,flags=2,startId=1
07-12 14:12:15.755: I/ActivityManager(218): Start proc com.miui.weather2 for broadcast com.miui.weather2/.service.ServiceUpdateWeather: pid=1484 uid=10060 gids={3003}
07-12 14:12:15.755: I/HadesLee(1456): nextRemindTime=null

看到此Log,发现它是收到android.intent.action.USER_PRESENT的广播后,进行服务的启动的。

android.intent.action.USER_PRESENT对应的手机屏幕的解锁,一般用户哪能有病没病的让手机一直在唤醒状态,所以我们可以通过接收此广播进行服务的重启,保持Service一直在后台运行。

在AndroidManifest.xml文件里注册该广播就OK,顺带贴下手机开机发送的广播。

<receiver android:name="com.agilemobi.comac.collect.android.services.UserPresentReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
<receiver android:name="com.agilemobi.comac.collect.android.services.BootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

public class UserPresentReceiver extends BroadcastReceiver {

	private static final String TAG = "UserPresentReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.e(TAG, "receive broadcast");
		// do something
	}
}

抱歉!评论已关闭.