Search code examples
androidtoast

Stop the toast while quitting the app


I was doing an application which uses some Toasts.

If a Toast appears and in the meanwhile I quit the app, it normally doesen't disappear.

Is there a way to stop the Toast if I quit the app on my phone?


Solution

  • In Activity onStop or ondestroy use cancel() method

    public class MainActivity extends Activity {
    private Toast toast = null;
    
    @SuppressLint("ShowToast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        showMyToast();
         }
    
    
       public void showMyToast()
       toast.setText(" test toast");
                toast.show();
      }
    
    @Override
    protected void onStop () {
        super.onStop();
        toast.cancel();
    }