确定Activity的启动方式

时间:2014-02-05 13:57:16

标签: android android-activity

我有一个应用程序,它首先启动一个不是MainActivity的活动,但是在应用程序的过程中可以自行启动活动。我想在活动关闭时运行的代码能够确定它是否应该在应用程序的前面(第一次运行),或者它是否应该返回到堆栈上的前一个Activity(所有其他运行)。是否可以确定Activity内部是如何启动的?

3 个答案:

答案 0 :(得分:1)

你说:

  

我想在孩子的课程中确定   活动什么父活动启动了孩子。在我的情况下,将   要么是Launcher,要么是MainActivity。

不幸的是,没有办法找出Activity推出了什么活动。这个信息是不可用的。然而...

您可以通过查看IntentACTION = MAIN的{​​{1}}来判断启动器是否启动了您的活动:

CATEGORY = LAUNCHER

您还可以通过检查Intent intent = getIntent(); if (Intent.ACTION_MAIN.equals(intent.getAction()) && intent.hasCategory(Intent.CATEGORY_LAUNCHER)) { // started by launcher } 来检查活动是否已从最近任务列表中启动:

Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY

如果这对您来说还不够,那么您可以在从父级启动子Activity时自己添加“额外”,以便它可以告诉Activity启动它。例如:

Intent intent = getIntent();
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
    // Launched from recent task list
}

然后在您的孩子活动中,您可以这样检查:

Intent intent = new Intent(this, ChildActivity.class);
intent.putExtra("startedFromMainActivity", true);
startActivity(intent);

答案 1 :(得分:0)

您可以在启动活动的意图中存储一个值,一旦打开,请阅读它以调整您的行为:

intent.putExtra(key,value);

在活动方面(例如onCreate):

getIntent().getExtra(key,defaultValue);

如果未找到任何值,则默认值为。 getExtra取决于存储的数据类型,因此有getIntExtra,booleanExtra,stringExtra ...
了解详情here

答案 2 :(得分:0)

  

你的宣言文件交换主要活动DEFAULT ...

      <activity
        android:name="com.example.iiintent.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.iiintent.al">
    <intent-filter>


            <category android:name="android.intent.category.LAUNCHER" />
    </activity>
相关问题