android – 完成后退按钮两次按下时的活动?

参见英文答案 > Leaving android app with back button13个
我正在创建一个应用程序,我需要完成活动,当用户两次按下后退按钮.这是我尝试的代码
@Override
public void onBackpressed() {
        super.onBackpressed();
        this.finish();
}

也试过这个

@Override
public boolean onKeyDown(int keyCode,KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
    finish();
}
return super.onKeyDown(keyCode,event);
}

这有助于我按下后退按钮完成活动.

请,我需要你的建议.提前致谢

解决方法

好的…这是一个更长但有效的方法来做到这一点……

1)在你的课堂上做一个全球可修复的…

private boolean backpressedToExitOnce = false;
private Toast toast = null;

2)然后实现onBackpressed这样的活动……

@Override
public void onBackpressed() {
    if (backpressedToExitOnce) {
        super.onBackpressed();
    } else {
        this.backpressedToExitOnce = true;
        showToast("Press again to exit");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                backpressedToExitOnce = false;
            }
        },2000);
    }
}

3)使用这个技巧有效地处理这种吐司…

/**
 * Created to make sure that you toast doesn't show miltiple times,if user pressed back
 * button more than once. 
 * @param message Message to show on toast.
 */
private void showToast(String message) {
    if (this.toast == null) {
        // Create toast if found null,it would he the case of first call only
        this.toast = Toast.makeText(this,message,Toast.LENGTH_SHORT);

    } else if (this.toast.getView() == null) {
        // Toast not showing,so create new one
        this.toast = Toast.makeText(this,Toast.LENGTH_SHORT);

    } else {
        // Updating toast message is showing
        this.toast.setText(message);
    }

    // Showing toast finally
    this.toast.show();
}

4)当你的活动关闭时,用这个技巧隐藏吐司……

/**
 * Kill the toast if showing. Supposed to call from onPause() of activity.
 * So that toast also get removed as activity goes to background,to improve
 * better app experiance for user
 */
private void killToast() {
    if (this.toast != null) {
        this.toast.cancel();
    }
}

5)实现你onPause()这样,当活动进入后台时杀死吐司

@Override
protected void onPause() {
    killToast();
    super.onPause();
}

希望这会有所帮助……

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...