我想在Android中創建永無止境的後臺服務。要做到這一點,我使用AlarmManager
與簡單Service
Alarmmanger
在一段時間後發送廣播,在廣播接收機我正在檢查服務正在運行,如果運行,然後什麼也不做,再次啓動它。當從最近的任務列表中殺死應用程序時,Android後臺服務永遠不會啓動
我的服務代碼是
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate ();
Log.e ("My service ", "oncreate");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
scheduleAlarm();
super.onTaskRemoved (rootIntent);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the ServiceAlarmReceiver
Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
6000, pIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e ("My Service:", " on Start Command");
return START_STICKY;
}
}
廣播接收機
public class ServiceReceiver extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE=12355;
public ServiceReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// check service is running or not
if (isMyServiceRunning (MessageService.class,context)){
// don nothing
}
else {
// launch the service
if (isConnectedToInternet (context)) {
Intent serviceIntent = new Intent (context, MyService.class);
context.startService (serviceIntent);
}
}
Log.e ("hello","wer are in Receiver");
// throw new UnsupportedOperationException ("Not yet implemented");
}
}
我的清單:
<receiver
android:name=".Services.ServiceReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="com.hmkcode.android.USER_ACTION" />
</intent-filter>
</receiver>
<service
android:name=".Services.MyService"
android:enabled="true"
android:stopWithTask="false"
android:process=":remote"
>
</service>
它工作得很好,當應用程序在前臺或後臺,但問題是當我從Android中的最近任務列表中掃出應用程序時,a pp因爲服務而死亡,我的廣播接收機無法再次啓動它?我在onTaskRemoved
方法中重新計劃了我的Alarmmanger
方法,但服務仍然沒有重新開始。
同樣返回START_STICKY
從onStartCommand()
正如人們所說的那樣,系統將重新啓動服務,即使必須停止資源限制。
也使用"stopWithTask"=false
在<service>
清單文件的標記。它也沒有影響。