-4

My requirement is when user swipes(destroys) my application from Recent tab, I want to show a toast. For this I tried showing the toast in onDestroy of the MainActivity, But the toast does not show up. I am using the following code :

Toast.makeText(this, "Toast", Toast.LENGTH_SHORT).show();

Can you help what could be the reason?

Rock
  • 47
  • 7
  • 1
    it should be onTabChanged – Keyur Lakhani May 18 '16 at 09:22
  • You should post the code else this would be just a guess work. Well, my guess: Put the toast before **super.onDestroy()** – NezSpencer May 18 '16 at 09:41
  • I used to show toast before super.onDestroy.. But no help. There is not much code here.. I just show a toast on onDestroy of activity. Scenario is : When my application is running, some background service is started and the work is being done. Now when my application is destroyed from recents page, I kill my process in onDestroy of MainActivity. Now before killing my process, I want to show a toast to user say like "service is stopped" – Rock May 18 '16 at 11:31

3 Answers3

1

The context becomes null so the Toast does not appear. You may put a log to see whether the code is executed on that line or not.

Atahar Hossain
  • 336
  • 3
  • 11
  • I already added a log. and the above line of code is executed – Rock May 18 '16 at 11:06
  • It is difficult to show Toast while the app destroys from the background. Can you please share what you want to do ? – Atahar Hossain May 18 '16 at 11:18
  • When my application is running, some background service is started and the work is being done. Now when my application is destroyed from recents page, I kill my process in onDestroy of MainActivity. Now before killing my process, I want to show a toast to user say like "service is stopped" – Rock May 18 '16 at 11:22
  • Just override the "onTaskRemoved" from Service classs which is called when the service is running and the user remove it from the backgroud. Now put the toast inside "onTaskRemoved" like - Toast.makeText(this, "Your Message", Toast.LENGTH_LONG).show(); – Atahar Hossain May 19 '16 at 04:45
0

you can write this code and see logcat

 @Override
protected void onDestroy() {
    super.onDestroy();
    Log.i("OnDestroy", "onDestroy: OnDestroy called");
}
Romil Jain
  • 305
  • 3
  • 5
0

Toast only shows up in onDestroy(), when you have called super.onBackPressed() either in onBackPressed() or in the beginning of onDestroy(). For example:

@Override
public void onBackPressed() {
    moveTaskToBack(false);
}

@Override
protected void onDestroy() {
    super.onBackPressed();
    Toast.makeText(getApplicationContext(), "You're offline!", Toast.LENGTH_SHORT).show(); 
    super.onDestroy();
}