1.問題
安裝apk程序成功後會有兩個按鈕,打開、完成。打開可以打開安裝的程序,此時操作程序。然後按home鍵再從桌面點擊圖標打開程序會發現程序從入口重新打開,並不是剛纔的運行狀態。
2.解決辦法
我們在程序入口的activity中檢測該activity是不是程序的root Activity。如果不是就可以直接finish此activity,程序會從棧中還原以前的狀態。
具體代碼如下:
在應用啓動的activity的Oncreate方法中添加如下代碼即可:
if (!isTaskRoot()) {
//bug at:http://blog.csdn.net/aa464971/article/details/62044798
// Android launched another instance of the root activity into an existing task
// so just quietly finish and go away, dropping the user back into the activity
// at the top of the stack (ie: the last state of this task)
finish();
return;
}
或者更加安全的做法:
if(!isTaskRoot()) { //判斷該Activity是不是任務空間的源Activity,“非”也就是說是被系統重新實例化出來
//如果你就放在launcher Activity中話,這裏可以直接return了
//bug at:http://blog.csdn.net/love100628/article/details/43238135
Intent mainIntent=getIntent();
String action=mainIntent.getAction();
if(mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
finish();
return;//finish()之後該活動會繼續執行後面的代碼,你可以logCat驗證,加return避免可能的exception
}
}
可以將上面的代碼加在setContentView(R.layout.xxx);之前;