标签:
1.在mainfest.xml中注册
<!-- 自启服务广播 -->
<receiver
android:name="com.bdkj.gmys.broadcast.BootBroadCast"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="com.bdkj.gmys.broadcast.Alarmreceiver" >
<intent-filter>
<action android:name="arui.alarm.action" />
</intent-filter>
</receiver>
2.设置监听(设置计时器,不定时去检查服务)
public class BootBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent mintent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(mintent.getAction())) {
// 启动完成
Intent intent = new Intent(context, Alarmreceiver.class);
intent.setAction("arui.alarm.action");
PendingIntent sender = PendingIntent.getBroadcast(context, 0,
intent, 0);
long firstime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 10秒一个周期,不停的发送广播
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
10 * 1000, sender);
}
}
}
public class Alarmreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("arui.alarm.action")) {
if (!isServiceWork(context, "com.easemob.chat.EMChatService")) {
// 环信service
Intent i = new Intent();
i.setClass(context, EMChatService.class);
context.startService(i);
}
if (!isServiceWork(context, "com.umeng.message.UmengService")) {
// 友盟service
Intent n = new Intent();
n.setClass(context, UmengService.class);
context.startService(n);
}
}
}
/**
* 判断某个服务是否正在运行的方法
*
* @param mContext
* @param serviceName
* 是包名+服务的类名(例如:net.loonggg.testbackstage.TestService)
* @return true代表正在运行,false代表服务没有正在运行
*/
public boolean isServiceWork(Context mContext, String serviceName) {
boolean isWork = false;
ActivityManager myAM = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> myList = myAM.getRunningServices(40);
if (myList.size() <= 0) {
return false;
}
for (int i = 0; i < myList.size(); i++) {
String mName = myList.get(i).service.getClassName().toString();
if (mName.equals(serviceName)) {
isWork = true;
break;
}
}
return isWork;
}
service开机启动及自启(由于android权限的控制,可能有问题)
标签:
原文地址:http://www.cnblogs.com/qwer520/p/5082187.html