0

I want to stop the delay/intent from processing when the back button is pressed. I've searched some threads but I don't have the same Handler logic, I think. I apologize if it is.

Here is the code I'm working with:

else {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent intent = new Intent(MainActivity.this, PollWebView_Gilmore.class);
                        startActivity(intent);
                        finish();

                    }

                }, 10000);

3 Answers3

1

You have to save a reference to both the Handler and your Runnable somewhere, and then you can use the removeCallbacks(Runnable) method on the Handler to cancel the pending request.

Example code:

public class MainActivity extends AppCompatActivity {

    private Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(MainActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.postDelayed(runnable, 5000);
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        handler.removeCallbacks(runnable);
    }

}
zsmb13
  • 85,752
  • 11
  • 221
  • 226
1

If you Don't need a delay why do you use a Handler? Just remove it!

Call this directly

Intent intent = new Intent(MainActivity.this, PollWebView_Gilmore.class);
startActivity(intent);
finish();

When your back button is pressed!

You can also get an idea by reading below posts.

Android: Proper Way to use onBackPressed() with Toast

How to run a Runnable thread in Android?

Community
  • 1
  • 1
0

If you want to do something with the intent on back pressed.You can override onBackPressed() method.

Jack
  • 308
  • 6
  • 15