OnTaskRemoved from an Android service is never called! What for?

I am stuck in a problem for the last 2 days, I want to click api and show Toast to the user when the user uninstalled the application from the background task, I found that it is possible from service , since onTaskRemoved is called when the application is removed from the background.

The code:

MyService.java

 public class MyService extends Service { private static final String TAG = MyService.class.getSimpleName(); Handler mHandler; @Override public void onCreate() { super.onCreate(); mHandler = new Handler(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand: "); mHandler.post(new Runnable() { @Override public void run() { new ToastPoP(MyService.this).showLongToast("Service started"); } }); return Service.START_STICKY; } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Log.d(TAG, "onTaskRemoved: "); mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(App.getInstance(), "Removed", Toast.LENGTH_SHORT).show(); // api call too } }); // for kitket Intent restartService = new Intent(getApplicationContext(), this.getClass()); restartService.setPackage(getPackageName()); PendingIntent restartServicePI = PendingIntent.getService( getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy: "); } } 

and in Manifest I added the following:

  <service android:name=".MyService" android:stopWithTask="false" > </service> 

and launched service in SplashScreen:

  Intent i = new Intent(this, MyService.class); this.startService(i); 

The service starts well, but onTaskRemoved never called when I remove the application from Background. What for? what am I doing wrong?

Note:

And the interesting result is that I can get Toast on some device, but not on most devices, and all devices have OS-Android 5.0

+6
android android-service
Oct 13 '16 at 12:39
source share
1 answer

Try this one

 <service android:name=".MyService" android:enabled="true" android:stopWithTask="false" /> 

Just replace Service.START_STICKY; at START_STICKY;

And you can call onTaskRemoved(Intent rootIntent) after removing or removing the application from the list of recent applications.

-3
Jan 10 '17 at 11:40
source share



All Articles