Android學習札記39:關於安全退出已創建多個Activity的應用(2)

谷歌百度一下,Android 中退出多個 Activity 的方法,大家討論的很多。


在實習的時候,看到公司的項目退出多個 Activity,是採用 LinkedList 方法,畢業設計的時候,也參照了那種方法。完成之時,無意在網上看到的可以使用廣播機制退出Activity。看了一部分人的博客、文章等教程,發現也是摘抄的“很隨便”,說的不詳細,或不能實現。


看了他們的意思,寫了 demo,大家看看吧。主要代碼如下:(不方便看的直接下整個工程)

爲了代碼的簡潔性,抽取出一個基類 BaseActivity(自定義的,當然,你也可以不寫這個基類,只要在你項目的每個Activity 裏實現其中的代碼即可),讓你代碼中要關閉的 Activity 都繼承這個 BaseActivity。

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();
		// 在當前的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);
	}
}

在你要關閉的 Activity 裏添加 myExit() 方法,然後在要進行退出程序操作的地方調用 myExit() 方法就行。

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);
			}
		});
	}


	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();
	}    
}


轉載自:

http://ldl8818.iteye.com/blog/1531021





發佈了42 篇原創文章 · 獲贊 5 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章