Android - Handler - How To Stop The Intent?

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);

Upvotes: 0

Views: 747

Answers (3)

zsmb13
zsmb13

Reputation: 89548

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);
    }

}

Upvotes: 1

user4252348
user4252348

Reputation:

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?

Upvotes: 1

Jack
Jack

Reputation: 328

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

Upvotes: 0

Related Questions