我有一个活动“DashboardActivity”(不是主要活动),我想在其中捕获 BACK 按钮以询问他们是否要注销(因为 BACK 通常会将您带到登录屏幕)。
我努力了
public void onBackPressed() {
// ask if they want to logout.....
logOutIfTheyReallyWantTo();
//super.onBackPressed();
}
但是在调试器中测试它似乎根本没有命中代码。
然后我尝试添加
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
这也证明是浪费时间。
最后我尝试了
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// a long press of the call key.
// do our work, returning true to consume it. by
// returning true, the framework knows an action has
// been performed on the long press, so will set the
// canceled flag for the following up event.
return true;
}
return super.onKeyLongPress(keyCode, event);
}
但调试器没有检测到它们。LogCat 只显示
05-29 12:22:59.040: D/NetdConnector(14366): RCV <- {217 0}
05-29 12:22:59.040: D/NetdConnector(14366): RSP <- {217 0}
05-29 12:23:04.743: V/processReply(32759): sr0857000000
05-29 12:23:07.673: W/KeyCharacterMap(32759): No keyboard for id 0
05-29 12:23:07.673: W/KeyCharacterMap(32759): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-29 12:23:07.907: V/Dashboard(32759): Pause
05-29 12:23:07.915: I/ComfortActivity(32759): start
05-29 12:23:07.915: V/ComfortActivity(32759): Resume
05-29 12:23:08.032: D/dalvikvm(14430): GC_EXPLICIT freed 92K, 52% free 3322K/6791K, external 5633K/7003K, paused 77ms
05-29 12:23:08.329: I/DashboardActivity(32759): stop
05-29 12:23:08.829: V/processReply(32759): sr0856000000
似乎有很多关于这个的问题,我已经尝试了所有我能找到的建议,但到目前为止还没有运气。
---- 回答问题....
void logOutIfTheyReallyWantTo()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Log out?");
alert.setMessage("Do you really want to log out?");
//AlertDialog loginPrompt = alert.create();
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
((ComfortApp) getApplicationContext()).soundClick();
getComms().logout(true);
Intent intent = new Intent(DashboardActivity.this, ConfigurationActivity.class);
startActivityForResult(intent, 0);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// just like Perry the Platypus....
// don't do much
((ComfortApp) getApplicationContext()).soundClick();
}
});
alert.show();
}