Post Delay Method - Android

杀马特。学长 韩版系。学妹 提交于 2019-12-01 07:44:28

问题


I used postedDelayed method to refresh my Activity, which works fine. But the problem is that even when I press the Back button postdelayed method call back the previous activity..

//handler for 30000 milli-secs post delay refreshment of the activity

mHandler.postDelayed(new Runnable() {
public void run() {
               dostuff();

        }
            }, 30000);
    }

protected void dostuff() {
Intent intent = getIntent();
finish();startActivity(intent);
Toast.makeText(getApplicationContext(), "refreshed", Toast.LENGTH_LONG).show();
}

public void onBackPressed() {
        super.onBackPressed();
        finish();
        mHandler.removeCallbacks(null);
        }

protected void onStop() {
            mHandler.removeCallbacks(null);
        super.onStop();
    }

回答1:


You can use removeCallbacks(runnable) method of the handler using which you are calling postDelayed() method. For example, if you used:

mHandler.postDelayed(mRunnable, mTime)

for refreshing the activity, then use

mHandler.removeCallbacks(mRunnable)

in onPause() method of the activity.




回答2:


Make a sign of boolean in your postdelayed method. Init the sign as true,when the activity is finnished , set the value of sign as false.




回答3:


You can use this piece of code to run after a 3 sec delay.

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {

        // run your code here    

    }
}, 3000);


来源:https://stackoverflow.com/questions/16050807/post-delay-method-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!