0

假设一个应用程序中只有 2 个活动:
1.活动 A(启动器活动)
2.活动 B


onCreate()中Acrivity A的代码:

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

因此,通过传递数据从Activity A启动Activity B 。活动 A也被破坏。


所以,如果我第一次启动应用程序:
1.活动 A启动
2.活动 A使用数据启动活动 B
3.活动 A被销毁

假设如果我从Activity B按下后退键,则Activity B被破坏并且应用程序退出,如果我重新启动应用程序:
1. Activity B 直接启动,获取从Activity A设置的相同数据。


我的问题是:
当应用程序重新启动时,我如何才能停止获取此意图?
活动 B重新启动后开始,不是问题,我只是想停止获取意图。


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>

4

1 回答 1

0

每次启动应用程序时,它都会运行 ActivityA。而且由于您告诉 ActivityA 在创建数据时将其发送到 ActivityB,因此它每次都会这样做。

听起来像第二次,你仍然想启动 ActivityB,但不是你在意图中额外输入的数据,对吗?无论您是否已发送该数据,您都需要跟踪应用程序的启动。一种方便的方法是 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();  

这将使 ActivityA 总是启动 ActivityB,但它只会在第一次发送数据。

于 2014-12-04T08:21:46.150 回答