如何保证Android Service不被系统杀死

来源:互联网 发布:linux故障排查 编辑:程序博客网 时间:2024/06/02 04:15

   网上看了许多关于这个的,百度或者其他软件推送消息时,保证让程序退出后仍然接收消息,网上写的比较乱,因此总结了一下。

1.AndroidManifest.xml模块

      <service
            android:name="MyNotificationService"
             android:enabled="true">
             <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
            </service>

   定义好你的service,并在anction规定启动方式:action android:name="android.intent.action.BOOT_COMPLETED



2.在你的service里面:


public class MyNotificationService extends Service{
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        return Service.START_STICKY;
    }
}

将onStartCommand返回Service.START_STICKY,这样就可以了。

系统将开一个进程,一直后台运行。

0 0
原创粉丝点击