简体   繁体   中英

How to open not main activity when restart my application in android

I made an app worked in background using background service when the user clicked specific button (start button) , the user can stop the application task by restart this application and open it again .. then the user can stop the app by clicking on the stop button.

I use this code snippet to let the app close its UI and return to home screen and before that set the start button on disable mode ...

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

Unfortunately, when I open my app again I start from the main activity which is not contains the start button and stop button and when I swipe to the second activity that contains the buttons I find the start button enabled ie the previous task of the background service is lost ??!!

could any one provide me by the solution.

You have to take a look at Android application lifecycles, when your app goes to the background it will get to the state onPause() and later to onStop() , what you want is saving your application state for later use, take a look at this thread: Saving Activity state in Android I think the top answer is what you want to do.

You have to save the status of your button, and then load the status later.

You could use SharedPreferences to store your wanted activity. Then check it right after MainActivity start, to decide change to new activity or not

//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();

Every time you open your app the buttons are enabled by default(excepting those which are disabled from the start).

So you need to saved this state to retain it's state. Here is how to retain and restore the state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM