2017-06-09 14 views
-3

サービスはMainActivityから開始されたときに正常に動作しますが、最近のアプリケーションからアプリケーションを削除したときや、アクティビティが終了したときに、中断した場所から続けるのではなくサービスが再開されます。サービスでアプリケーションが実行されない

public class ServiceExample extends Service { 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO: Implement this method 
    return null; 
} 

@Override 
public void onCreate() { 
    // TODO: Implement this method 
    super.onCreate(); 
    //Do Something 
} 

バックグラウンドでアクションを実行する必要がありますが、アクティビティが終了すると停止または再開できません。サービスステートメントは、使用するのに最適ですか?

答えて

0

サービスクラスの中に入れてみてください。

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

これにサービスを提供して上書きするコードの下に追加します。 –

+0

START_NOT_STICK;サービス終了 –

0

もサービスを再起動するようにするonStartCommandreturn START_STICKY

@Override 
public void onTaskRemoved(Intent rootIntent){ 
    Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass()); 
    restartServiceTask.setPackage(getPackageName());  
    PendingIntent restartPendingIntent = PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT); 
    AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
    myAlarmService.set(
      AlarmManager.ELAPSED_REALTIME, 
      SystemClock.elapsedRealtime() + 1000, 
      restartPendingIntent 
    ); 

    super.onTaskRemoved(rootIntent); 
} 
+0

このメイクサービスは再開されました –