Getting Intent when App re-launch

502 views Asked by At

Suppose there are only 2 Activities in an Application :
1. Activity A (Launcher Activity)
2. Activity B


Code for Acrivity A in onCreate() :

Intent intent = new Intent();
    intent.putExtra("key", "test");
    intent.setClass(this, ActivityB.class);
    startActivity(intent);
    finish();  

So, launching Activity B from Activity A, by passing a data. Also Activity A get destroyed.


So, if I launch the app for first time :
1. Activity A started
2. Activity A launches Activity B with a data
3. Activity A get destroyed

Suppose If I press the back key from Activity B, Activity B get destroyed and the application get exit and if I re-launch the app :
1. Activity B get started directly, getting the same data, that was set from Activity A.


My Question is :
How Can I stop getting this intent when app get re-launched ?
Activity B started after re-launch, is not an issue, I just wanted to stop getting the intent.


AndriodManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.listnertest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="ActivityA"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="ActivityB"
        android:label="@string/app_name" >
    </activity>
</application>

1

There are 1 answers

1
Bruce On

Every time you launch the app, it's going to run ActivityA. And since you are telling ActivityA to send that data to ActivityB whenever it is created, it's going to do that every time.

It sounds like on the second time, you still want to launch ActivityB, but not with the data you put in the intent extra, is that right? You would need to keep track across app launches whether you have sent that data yet. A convenient way to do that is SharedPreferences.

Intent intent = new Intent();
SharedPreferences prefs = activity.getSharedPreferences("my_prefs", 0);
if (!prefs.contains("sent_key")) {
    intent.putExtra("key", "test");
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("sent_key", true);
    editor.commit();
}
intent.setClass(this, ActivityB.class);
startActivity(intent);
finish();  

This will make ActivityA always launch ActivityB, but it would only send the data the first time.