2017-04-09 15 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+ –

関連する問題