tl; dr:問題底部的方法是退出Android應用程序的合理方法嗎?我的方法是明智地退出Android應用程序嗎?
我維護一個Android音樂播放器應用程序。 Source。
我已經收到了一些'退出按鈕集成到播放器的請求。 Issue。我爲每項活動的菜單添加了退出選項,例如
我已經嘗試了一些方法來退出應用程序,其中包括:
這兩種方法都存在一些問題。第一種方法從未奏效 - 我會按照示例中所述調用startActivity,但活動收到的意圖從未包含我的「退出」標誌。
第二種方法大部分時間工作,但如果我允許Android在我的揹包中銷燬活動,然後單擊退出,活動將重新啓動(顯然在收到「退出」廣播後)。我可以通過使用開發人員選項在離開視圖後立即銷燬所有活動,從而始終可以重新創建此問題。
我上解決的方法是廣播一個「退出」的消息和明確啓動主屏幕:
if (id == R.id.action_exit) {
// I had issues just broadcasting the "exit" intent
// if the other activities on the stack had finished,
// they were re-created, presumably *after* the broadcast had been sent
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.smithdtyler.ACTION_EXIT");
sendBroadcast(broadcastIntent);
// To make sure we exit, *first* send the broadcast (this makes sure the MusicPlaybackService shuts down)
// then launch the home screen
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startMain);
finish();
return true;
}
完整的源代碼,以我的退出方法是可用here。
這種方法一直在測試,但我很好奇,如果有可能的用戶配置,我可以忽略這可能會導致問題。
那些誰downvoted - 請你評論和解釋爲什麼? – 2015-02-10 14:14:00