Search code examples
androidandroid-activitytimerbackground-servicedata-persistence

Keep an activity/activities alive while the app is open in the background


Hey guys I'm brand new to this site, I know people get put down a lot for asking duplicated questions so I hope this isn't one of them.

As well as this site, I am new to android programming and have created a simple app for calculating a price based on time.

this app has 3 activities that i use to switch layouts 1. FirstActivity - shows title page and button to launch second activity 2. SecondActivity - starts a timer and calculates price based on seconds. 3. LastActivity - shows the end results of time and price and allows the user to share this with other apps (email, sms)

Everything is working fine, however when the phone orientates the current activity is killed and restarted I've fixed this by forcing the layout to portrait - I've now run into this problem again when i move the app to the background

SO THE ACTUAL QUESTION: I need my SecondActivity to keep time, and my LastActivity to keep the saved info even if the user switches apps. I'm not talking about when the app is closed im talking about when the app switcher or home button are activated and my app is still open in the background.

thank you in advance!


Solution

  • So in the end I just needed more information on how to implement the Data Save features that everyone suggested and that android has, I found the answer I needed here: How to make an android app return to the last open activity when relaunched?

    To solve the problem I needed to add: |1| a new Activity |2| <action> and <category> tags to the activity |3| SharedPreference setters in each activity I needed to keep.

    1. Per @JosefPfleger's intructions I made a new blank activity named RestorePrevActivity and in the android manifest set it as MAIN and LAUNCHER and DEFAULT I also removed all the intent filters in my first activity as they were defaulted there after creating the app for the first time.

       <activity
         android:name=".FirstActivity"
         android:label="@string/app_name"
         android:screenOrientation="portrait" >
       </activity>
       <activity
         android:name=".SecondActivity"
         android:label="@string/title_activity_second"
         android:screenOrientation="portrait"
         android:launchMode="standard">
       </activity>
       <activity
         android:name=".LastActivity"
         android:label="@string/title_activity_last"
         android:screenOrientation="portrait"
         android:launchMode="standard">
       </activity>
       <activity
         android:name=".RestorePrevActivity"
         android:label="@string/title_activity_main" >
         <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
           <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
       </activity>
      
    2. After setting the action and category of my new activity i needed to add code to the activity. this was added to onCreate() of RecoverPrevActivity

    `

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Class<?> activityClass;
    
        try {
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
            activityClass = Class.forName(
                    prefs.getString("lastActivity", FareActivity.class.getName()));
        } catch(ClassNotFoundException ex) {
            activityClass = FareActivity.class;
        }
    
        startActivity(new Intent(this, activityClass));
    }
    

    where FirstActivity Would be replaced with the default activity you would run if no previous activity could be found.

    1. finally I went through my activities and added an OnPause() that saved the activity name.

    I added the following code segment to all my other activities and now its working flawlessly.

    @Override
    protected void onPause() {
        super.onPause();
    
        SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("thisActivity", getClass().getName());
        editor.commit();
    }
    

    Where thisActivity is changed to the name of the current activity.

    Result I was able to launch my app, start the timer and then press the home button or app switcher to safely switch apps or even lock the screen and upon return it successfully brought back my timer that was running uninterrupted! I put it to another test and ran clash of clans, a memory heavy game and I also watched Youtube videos for about 30 with my app running in the background and came back to my app to see the time was correct and ran perfectly while I was gone.