Android中让Service被关闭后再重新启动

时间:2022-11-02 16:41:34

转自:http://blog.csdn.net/rex_amaker/article/details/7049039

如何做到开机启动?

只要实现一个BroadcastReceiver,监听手机启动完成的事件ACTION_BOOT_COMPLETED即可。需要注意的是,好像不能用模拟器,要用手机测试。

那如何做到启动一个Service,并且在用户关闭后能自动又启动了呢?

一般的,都会在上面说到的BroadcastReceiver的实现里面,监听手机启动完成后,启动一个Service,这是一般的做法。问题是,用户可以关闭掉该Service。那么怎样才能使它被关闭掉以后,再次启动呢?聪明的你一定立即就想到了,如果不直接启动Service,而是启动一个timmer,或者alarmManager,然后每隔一段时间去启动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该做的事
}
}

    <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>