為了代碼的簡潔性,抽取出一個(gè)基類BaseActivity(自定義的,當(dāng)然,你也可以不寫這個(gè)基類,只要在你項(xiàng)目的每個(gè)Activity里實(shí)現(xiàn)其中的代碼即可),讓你代碼中要關(guān)閉的Activity都繼承這個(gè)BaseActivity。 [php] public class BaseActivity extends Activity { protected BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; @Override public void onResume() { super.onResume(); // 在當(dāng)前的activity中注冊廣播 IntentFilter filter = new IntentFilter(); filter.addAction("ExitApp"); this.registerReceiver(this.broadcastReceiver, filter); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); this.unregisterReceiver(this.broadcastReceiver); } }[/php] 在你要關(guān)閉的Activity里添加myExit()方法,然后在要進(jìn)行退出程序操作的地方調(diào)用myExit()方法就行。 [php] public class Activity1 extends BaseActivity { private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.a1); btn1 = (Button)findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Activity1.this, Activity2.class); startActivity(i); } }); } /** * 捕獲手機(jī)物理菜單鍵 */ private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){//&& event.getAction() == KeyEvent.ACTION_DOWN if((System.currentTimeMillis()-exitTime) > 2000){ Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { myExit(); } return true; } return super.onKeyDown(keyCode, event); } protected void myExit() { Intent intent = new Intent(); intent.setAction("ExitApp"); this.sendBroadcast(intent); super.finish(); } }[/php]
發(fā)表評(píng)論