Toast Problems Android Alerts

1

I have these codes in my MainActivity.java I intend to show a toast type alert with a duration of one second and that if I give it 50 times and I stop pressing it does not keep appearing, that the previous ones are canceled.They do not appear when I change to another application, when I leave it in the background or close it. but even though these codes work. When I open another application the ondestroy and onstop methods and especially the toast.cancel I close the activity and it does not let me return with the backbutton anyone knows how to solve it there is some alternative to toast.cancel that does not give me these problems.

 final Toast toast = Toast.makeText(getApplicationContext(), "El mensaje dura 1 segundo", Toast.LENGTH_SHORT);
        toast.show();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {



            @Override
            public void run() {

                    toast.cancel();


            }
        }, 900);




@Override
protected void onStop () {
    super.onStop();

    toast.cancel();
}

@Override
protected void onDestroy() {
    super.onDestroy();

    toast.cancel();
}
    
asked by MBS.corp 15.01.2018 в 18:59
source

1 answer

1

You must define the variable toast globally of your class

private Toast toast;

and call the method of the Toast instance:

 toast = Toast.makeText(getApplicationContext(), "El mensaje dura 1 segundo", Toast.LENGTH_SHORT);
        toast.show();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {     

            @Override
            public void run() {

                    toast.cancel();

            }
        }, 900);

Remember that if you want to cancel the Toast when sending your application to the background, you should use the onPause()

method
@Override
protected void onPause () {
    super.onPause();
   //Cancela!
    toast.cancel();
}
    
answered by 15.01.2018 в 23:16