閱讀218 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android 2.2完全退出程序, 使用廣播機製

 這個問題一直困擾著我,試了n種方式,都不行,在網上搜了一圈,沒有能用的:

1.ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(package);
不行

2.android.os.Process.killProcess(android.os.Process.myPid());
也不行

3.manager.restartPackage(package);
還是不行


4.
Intent MyIntent = new Intent(Intent.ACTION_MAIN);
MyIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(MyIntent);
finish();
這個隻是退回到桌麵,如果打開多個Activity關閉重新打開也會有問題,還是還是不行

看到有說廣播機製,發現是個好東東,能徹底解決這個問題,廢話不說看代碼:
public abstract class EnterActivity extends BaseActivity {
...
	// 寫一個廣播的內部類,當收到動作時,結束activity
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			unregisterReceiver(this); // 這句話必須要寫要不會報錯,不寫雖然能關閉,會報一堆錯
			((Activity) context).finish();
		}
	};

	@Override
	public void onResume() {
		super.onResume();

		// 在當前的activity中注冊廣播
		IntentFilter filter = new IntentFilter();
		filter.addAction(Attribute.PAGENAME);
		registerReceiver(this.broadcastReceiver, filter); // 注冊
	}

	/**
	 * 關閉
	 */
	public void close() {
		Intent intent = new Intent();
		intent.setAction(Attribute.PAGENAME); // 說明動作
		sendBroadcast(intent);// 該函數用於發送廣播
		finish();
	}
...
}

最後更新:2017-04-02 06:52:09

  上一篇:go errno <errno.h> <cerrno>
  下一篇:go Google Flash轉換HTML5工具Swiffy測試版發布