解析Android中如何做到Service被关闭后又自动启动的实现方法
投稿:jingxian
本篇文章是对在Android中如何做到Service被关闭后又自动启动的方法进行了详细的分析和介绍。需要的朋友参考下
还是看下面的全部代码吧,不过多解释了。这些代码中还是有不少概念的,不熟悉AlarmManager、PendingIntent、BroadcastReceiver、Service等等这些概念的同学可以百度一下。
复制代码 代码如下:
package com.arui.framework.android.daemonservice;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
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);
}
}
}
复制代码 代码如下:
package com.arui.framework.android.daemonservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Alarmreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("arui.alarm.action")) {
Intent i = new Intent();
i.setClass(context, DaemonService.class);
// 启动service
// 多次调用startService并不会启动多个service 而是会多次调用onStart
context.startService(i);
}
}
}
复制代码 代码如下:
package com.arui.framework.android.daemonservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class DaemonService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.v("=========", "***** DaemonService *****: onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
Log.v("=========", "***** DaemonService *****: onStart");
// 这里可以做Service该做的事
}
}
下面是manifest文件的代码。
复制代码 代码如下:
<receiver
android:name=" com.arui.framework.android.daemonservice.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.arui.framework.android.daemonservice.Alarmreceiver" >
<intent-filter>
<action android:name="arui.alarm.action" />
</intent-filter>
</receiver>
<service
android:name="com.arui.framework.android.daemonservice.DaemonService" >
</service>