2017-04-09 153 views
0

我想創建一個即使在應用程序從任務管理器關閉時也會運行的service。我創建了一個服務,然後記錄了一條消息以檢查它是否正在運行,並且我注意到它只在應用程序正在運行或處於前景時才起作用。Android服務在應用程序死亡後停止

服務類:

public class CallService extends Service { 

    private final LocalBinder mBinder = new LocalBinder(); 
    protected Handler handler; 

    public class LocalBinder extends Binder { 
     public CallService getService() { 
      return CallService .this; 
     } 
    } 

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

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

    } 

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

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.d("TESTINGSERVICE", "Service is running"); 
    } 
} 

開始從我的MainActivity服務:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 
    startService(new Intent(this, CallService.class)); 

清單

<application> 
    ... 
    <service 
     android:name=".activities.services.CallService"> 
    </service> 
</application> 

我必須做什麼改變?謝謝,夥計

回答

2

在您的服務中,添加以下代碼。

@Override 
public void onTaskRemoved(Intent rootIntent){ 
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass()); 
    restartServiceIntent.setPackage(getPackageName()); 

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT); 
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME, 
    SystemClock.elapsedRealtime() + 1000, 
    restartServicePendingIntent); 

    super.onTaskRemoved(rootIntent); 
} 
+0

感謝這工作:) – Dinuka

+0

OMG這個工程就像魔術。 1+爲你 –

相關問題