Skip to content
Advertisement

How to open recent avtivity after app reopen in android studio

How to open recent activity after app reopen in android studio For Example, we create a book application Then after reopening the app, open the last page where we are

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Demo4">
    <activity android:name=".MainActivity2"></activity>
    <activity android:name=".MainActivity"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>



       

Advertisement

Answer

Create a Default activity as a launcher activity `public class Default extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_default);

 SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);


    String str = mPrefs.getString("activity", "1");
    if (str.equals("1")) {

        Intent intent = new Intent(Default.this,MainActivity.class);
        startActivity(intent);
        Toast.makeText(getApplicationContext(),"Hello 1",Toast.LENGTH_SHORT).show();
    } else if (str.equals("2")){

        Intent intent = new Intent(Default.this,MainActivity2.class);
        startActivity(intent);
    }
}
public void clickD(View view)
{
    Intent intent = new Intent(Default.this,MainActivity.class);
    startActivity(intent);
}

}`

//In MainActivity while saving preferences use: `public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    SharedPreferences mPrefs = getSharedPreferences("IDvalue", 0);
   SharedPreferences.Editor editor = mPrefs.edit();
    editor.putString("activity","1");
    editor.apply();
}
public void click(View view)
{
    Intent intent = new Intent(MainActivity.this,MainActivity2.class);
    startActivity(intent);
}

}`

//In MainActivity2 while saving preferences use: ` public class MainActivity2 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    SharedPreferences mPrefs = getSharedPreferences("IDvalue", 0);
    SharedPreferences.Editor editor = mPrefs.edit();
    editor.putString("activity","2");
    editor.apply();
}

}`

Advertisement