Hello devs!
This post is going to tell you a way to open the last opened activity in Android.
There are cases where we keep a login for the app and we need to use that login every time we open the app. However, you see in good apps, you don't need to login each time unless you logout. Following are the ways to achieve this:
1. Firebase Auth- this is the simplest way. However, if you don't want to use Firebase or have your own API, check out the next method.
2. SharedPreferences - Following is the way to make use of that:
1. In every activity you wish to open, add the following code.
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.commit();
}
This could be your MainActivity and your LoginActivity.2. Next, create a class called as DispatcherClass with the following code-
public class DispatcherClass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class<?> activityClass;
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(
prefs.getString("lastActivity", DefaultActivity.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = LoginActivity.class;
}
startActivity(new Intent(this, activityClass));
finish();
}
}
Here the DefaultActivity could be your LoginActivity or MainActivity.
3. Now, we need to edit the AndroidManifest.xml file-
Add the following activity-
<activity android:name=".activities.DispatcherClass">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
At the same time, remove the following from other activities(if present)-
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
This tells the default opening activity.
4. (Optional) This is sufficient to get the functionality. But at times, we need to send values from one activity to another. We usually use .putExtra(key,value) and .getExtra(key) to do that. However, if you are using the above method, the app will crash as we are not actually passing from screens. In that case, you need to use SharedPreferences. Here's how you store data-
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key","value");
editor.commit();
And in order to remove that key, use-
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("key");
editor.apply();
That's all folks! Hope you find this useful.
Credits-https://stackoverflow.com/questions/2441203/how-to-make-an-android-app-return-to-the-last-open-activity-when-relaunched
Comments
Post a Comment