cxq234843654的专栏

最近在搞不被系统杀死的Service,,网上查了好多,大致的方法是:

1、修改Service的onStartCommand方法

public int onStartCommand(Intent intent, int flags, int startId) {flags = START_STICKY;return super.onStartCommand(intent, flags, startId); } 2、在Service的onDestroy方法下修改如下:

@Overridepublic void onDestroy() {// TODO Auto-generated method stub// 为了防止被kill,需要在此方法中重启一下ServiceIntent service_intent = new Intent(this, RecordService.class);startService(service_intent);super.onDestroy();}3、自己写一个广播,在OnReceive方法里边startService

//用来处理需要重启手机,需要启动过应用以后才会生效public class BootCompletedReceiver extends BroadcastReceiver {Intent recordServiceIntent;static final String action_boot = "android.intent.action.BOOT_COMPLETED";@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(action_boot)) {recordServiceIntent = new Intent(context,RecordService.class);context.startService(recordServiceIntent);}}}}4、修改Manifest文件

a、加权限

<!– 开机自启动权限 –><span style="color:#ff6666;"><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /></span>

b、注册广播

<receiver android:name=".BootCompletedReceiver" ><intent-filter><!– 开机广播 –><span style="color:#ff6666;"> <action android:name="android.intent.action.BOOT_COMPLETED" /></span></intent-filter></receiver>

c、修改application属性

<applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"<span style="color:#ff6666;">android:persistent="true"</span>android:theme="@style/AppTheme" >d、修改Service的权限

<serviceandroid:name="com.test.service.RecordService"android:priority="1000" ></service>我在网上查的资料大致就是这样,按部就班,居然么有用!很火大!

最后用谷歌的两行代码搞定

就是在service的onCreate方法里边:

@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Notification notice = new Notification();startForeground(1, notice);}

这个方法据说是谷歌提供的,解释如下:

如果要启动一个不会被杀死的服务都要通知用户,只要通知了用户以后服务就不会被杀死,但是一旦清除这些通知,服务一样会被杀死,我们这里采用投机取巧的办法,让服务不会被第三方任务管理器杀死。

生命有限,努力无限

cxq234843654的专栏

相关文章:

你感兴趣的文章:

标签云: