2015-11-06 148 views
1

我正在嘗試創建一個後臺服務,每隔10分鐘就會調用一次,執行一個任務,並且在應用程序關閉時不會終止。爲什麼後臺服務在應用程序關閉時停止工作?

以下是代碼片段:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_location_service); 

    Intent intent = new Intent(this, AlarmReceiverLifeLog.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Calendar calendar = Calendar.getInstance(); 
    alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10 * 60 * 1000, pendingIntent); 
} 

onCreate,它會調用AlarmReceiverLifeLog類每十分鐘。以下是AlarmReceiverLifeLog類的代碼:

public class AlarmReceiverLifeLog extends BroadcastReceiver { 
    static Context context; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent ll24Service = new Intent(context, LifeLogService.class); 
     context.startService(ll24Service); 
    } 
} 

public class LifeLogService extends Service { 


    @Override 
    public void onCreate() { 
     super.onCreate(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
    } 

    @Override 
    public void onTaskRemoved(Intent rootIntent) { 
     Intent restartService = new Intent(getApplicationContext(), this.getClass()); 
     restartService.setPackage(getPackageName()); 
     PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); 
     Calendar calendar = Calendar.getInstance(); 
     AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
     alarmService.set(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis() + 100, restartServicePI); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
} 

我無法弄清楚什麼我已經錯過了。當我關閉應用程序時,後臺服務正在死亡。

任何人都可以提出任何關於此?

+0

你需要擴展intentservice,創建一個單獨的線程來執行你的任務,然後服務將持續 – Bhargav

回答

0

當應用程序關閉時,服務也會關閉,也是因爲它們位於一個線程中,所以服務應該放在另一個線程上,以防止它被關閉,查看該服務並查看是否使服務保持活動狀態報警管理器這裏的一個例子http://www.vogella.com/articles/AndroidServices/article.html這樣你的服務將不會顯示在通知中。

相關問題