I am stuck with a issue from last 2 days, I want to hit a api
and show user a Toast
when user swipe off the app from Background Task, I found that from service
it is possible as onTaskRemoved
is called when app is removed from background.
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 have added this :
<service android:name=".MyService" android:stopWithTask="false" > </service>
and started service
in SplashScreen :
Intent i = new Intent(this, MyService.class); this.startService(i);
Service is started well but onTaskRemoved
is never called when i am removing app from Background. Why ? what i am doing wrong?
Note:
And Interesting result is this i am able to get Toast in some device but not in most of the devices and all device's have OS- Android 5.0