【已解决】Android 如何让应用在后台运行
應(yīng)用在后臺(tái)跑,這種說法可能不夠準(zhǔn)確,就是說應(yīng)用沒有finish退出,但也不在前臺(tái)的狀態(tài),例如應(yīng)用執(zhí)行中點(diǎn)擊了home鍵一樣。如何實(shí)現(xiàn)呢?
要點(diǎn):
退回后臺(tái)是執(zhí)行了home鍵,activity分別執(zhí)行了onPause和onStop,應(yīng)用沒有被銷毀,退回后臺(tái)而已,再次運(yùn)行應(yīng)用只要執(zhí)行onResume就可以了。
?完全退出,執(zhí)行finish,activity會(huì)執(zhí)行onPause,onStop和onDestroy,應(yīng)用被銷毀,會(huì)被系統(tǒng)優(yōu)先回收,再次運(yùn)行應(yīng)用要執(zhí)行onCreate重新開始。
1.執(zhí)行home鍵
private ResolveInfo homeInfo;
public void onCreate(Bundle savedInstanceState) {
???????super.onCreate(savedInstanceState);
???????setContentView(R.layout.main);
? ??????PackageManager pm = getPackageManager();
??????? homeInfo =pm.resolveActivity(newIntent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
//工作內(nèi)容
?
//工作內(nèi)容
??? goToIdle();
}
?
?
private void goToIdle(){
??????? ActivityInfo ai =homeInfo.activityInfo;
??????? Intent startIntent= new Intent(Intent.ACTION_MAIN);
???????startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
???????startIntent.setComponent(new ComponentName(ai.packageName,
??????????????? ai.name));
???????startActivitySafely(startIntent);
??? }
??
??? voidstartActivitySafely(Intent intent) {
???????intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
??????? try {
???????????startActivity(intent);
??????? } catch(ActivityNotFoundException e) {
???????????Toast.makeText(this, "work wrongly",
???????????????????Toast.LENGTH_SHORT).show();
??????? } catch(SecurityException e) {
???????????Toast.makeText(this, "notsecurity",Toast.LENGTH_SHORT).show();
???????????Log.e(TAG,"Launcher does not have the permission to launch "
??????????????????????????????????? + intent
??????????????????????????????????? + ".Make sure to create a MAIN intent-filter for the corresponding activity "
??????????????????????????????????? + "oruse the exported attribute for this activity.",
???????????????????????????e);
??????? }
??? }
?
2.back鍵重寫執(zhí)行home鍵功能
public boolean onKeyDown(int keyCode, KeyEvent event) {
??????? if (keyCode ==KeyEvent.KEYCODE_BACK) {
??????????? goToIdle();
??????????? return true;
??????? } else
??????????? returnsuper.onKeyDown(keyCode, event);
??? }
?
?
3.重寫finish(),
??? @Override
??? public void finish() {
???????//super.finish();//activity永遠(yuǎn)不會(huì)自動(dòng)退出了,而是處于后臺(tái)。
???????moveTaskToBack(true);
??? }
補(bǔ)充:
本人在做傳感器數(shù)據(jù)的采集中,當(dāng)程序界面退出(按back鍵,或者按home鍵)時(shí),數(shù)據(jù)就不會(huì)輸出。所以我嘗試做如下簡(jiǎn)單修改,取得理想效果,故在此分享。
未修改前代碼:
protected void onStop() {super.onStop();sm.unregisterListener(this);}
修改后代碼(達(dá)到自己想要效果):
protected void onStop() {super.onStop(); // sm.unregisterListener(this); //將該行注釋掉,從而保證在退出時(shí)不注銷傳感器監(jiān)聽器}
總結(jié)
以上是生活随笔為你收集整理的【已解决】Android 如何让应用在后台运行的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: synchronized(this)用法
- 下一篇: Android基站定位