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