在android中重启我的应用程序时如何打开不是主要活动

时间:2015-06-03 09:05:21

标签: java android user-interface

当用户点击特定按钮(开始按钮)时,我使用后台服务在后台工作,用户可以通过重新启动此应用程序并再次打开来停止应用程序任务..然后用户可以通过单击停止应用程序在停止按钮上。

我使用此代码段让应用关闭其UI并返回主屏幕,然后在禁用模式下设置启动按钮...

           Intent intent = new Intent(Intent.ACTION_MAIN);
           intent.addCategory(Intent.CATEGORY_HOME);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           startActivity(intent);

不幸的是,当我再次打开我的应用程序时,我从主活动开始,它不包含开始按钮和停止按钮,当我滑动到包含按钮的第二个活动时,我发现启动按钮启用,即上一个任务后台服务丢了?? !!

任何人都可以通过解决方案为我提供帮助。

3 个答案:

答案 0 :(得分:0)

你必须看看Android应用程序的生命周期,当你的应用程序进入后台时,它将进入状态onPause(),然后进入onStop(),你想要的是保存你的应用程序状态以后使用,看一下这个帖子:Saving Activity state in Android我认为最好的答案是你想做的。

您必须保存按钮的状态,然后稍后加载状态。

答案 1 :(得分:0)

您可以使用SharedPreferences存储您想要的活动。 然后在MainActivity开始后立即检查,以决定是否更改为新活动

//check when start app
public class MainActivity extends Activity{
    public static SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

    sharedpreferences = getSharedPreferences("WantedActivity", Context.MODE_PRIVATE);
        if (sharedPreferences.contains("SavedActivityName"))
        {
            if(sharedPreferences.getString("SavedActivityName","").equals( "ActivityName"))
            {
                Intent intent = new Intent(getApplicationContext(), ActivityName.class);
                startActivity(intent);
            }
        }
    }
}

//save wanted activity


SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("SavedActivityName", "ActivityName");
    editor.commit();

答案 2 :(得分:0)

每次打开应用程序时,默认情况下都会启用按钮(除了从开始时禁用的按钮)。

  

所以你需要保存这个状态以保持它的状态。   Here   是如何保持和恢复国家。