防止服务被杀死的方法
//注册Intent.ACTION_TIME_TICK过滤器的接收器,每分钟接收一次
IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
NoKillReceiver receiver = new NoKillReceiver();
registerReceiver(receiver, filter);
MainActivity.startActivity=this;
//接收器代码,接收一次就判断需要打开的服务是否还在运行,如果已经被关闭折再次启动
package com.caicai.receiver; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.caicai.service.PushService; public class NoKillReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { boolean isServiceRunning = false; ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) { if("com.caicai.service.caiPushService".equals(service.service.getClassName())) { isServiceRunning = true; } } Intent i = new Intent(context, PushService.class); context.startService(i); if (!isServiceRunning) { }else{ Log.i("tt", "166666666666666666666666"); } } } }
//需要启动的服务
package com.caicai.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class PushService extends Service{ @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { Log.i("tt", "15555555555555555555555555555555555555555555555555555"); } }
posted on 2014-02-27 11:21 clarenceV1 阅读(340) 评论(0) 编辑 收藏 举报