欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现Service重启的方法

程序员文章站 2023-02-02 11:19:00
本文实例讲述了android实现service重启的方法。分享给大家供大家参考。具体如下: 做app的时候,我们可能需要一个后台服务一直在运行着,得用到service组件...

本文实例讲述了android实现service重启的方法。分享给大家供大家参考。具体如下:

做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
  }
}

希望本文所述对大家的android程序设计有所帮助。