「Android開発」ダブルクリック戻る、アプリケーションを終了する方法

1.ダブりクリック処理クラスの定義
DoubleClickExitHelper_startnews24.java

public class DoubleClickExitHelper_startnews24
{
private final Activity mActivity;
private boolean isOnKeyBacking;
private Handler mHandler;
private Toast mBackToast;
public DoubleClickExitHelper_startnews24(Activity activity)
{
mActivity = activity;//activityを保存
mHandler = new Handler(Looper.getMainLooper());//handlerを生成し、メッセージキューを管理
}

/**
* Activity onKeyDown関数
* */
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode != KeyEvent.KEYCODE_BACK)
{
return false;
}
if (isOnKeyBacking)
{
mHandler.removeCallbacks(onBackTimeRunnable);//メッセージキューを削除
if (mBackToast != null)
{
mBackToast.cancel();
}
//終了
mActivity.finish();
return true;
}
else
{
isOnKeyBacking = true;
if (mBackToast == null)
{
mBackToast = Toast.makeText(mActivity, R.string.back_exit_tips, 2500);
}
mBackToast.show();
mHandler.postDelayed(onBackTimeRunnable, 2500);//2500ms後に実行
return true;
}
}

// isOnKeyBackingをfalseに設定
private Runnable onBackTimeRunnable = new Runnable()
{
@Override
public void run()
{
isOnKeyBacking = false;
if (mBackToast != null)
{
mBackToast.cancel();
}
}
};
}

2.メインインタフェース呼び出し
Main.java
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ダブルクリック戻るキーを終了
mDoubleClickExitHelper_startnews24 = new DoubleClickExitHelper_startnews24(this);
}

/**
* プログラムを終了するかどうか
*/
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean flag = true;
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// アプリケーションを終了するかどうか
return mDoubleClickExitHelper_startnews24.onKeyDown(keyCode, event);
}
else if (keyCode == KeyEvent.KEYCODE_MENU)
{
//
}
else if (keyCode == KeyEvent.KEYCODE_SEARCH)
{
//
}
else
{
//
}
return flag;
}

Comments are closed.