【发布时间】:2015-05-13 08:07:39
【问题描述】:
在我正在进行的一个项目中,我遇到了接收外部意图的问题,即非启动器意图。我有一个Activity,可以使用普通的LAUNCHER 意图启动,但它也响应来自其他应用程序的SEND 意图,例如在 YouTube 应用中分享视频链接。我第一次分享来自其他应用程序的链接时,我的Activity 被创建,我可以使用getIntent() 来获取意图的详细信息,即EXTRA_TEXT。如果我关闭我的Activity 并使用另一个链接重试,那也可以。但是,如果我不关闭我的Activity,通过“主页”或“最近启动的应用程序”返回另一个应用程序,并分享另一个链接,我的Activity 会回到前台,但getIntent() 结果在旧意图中,而不是我认为会触发我Activity重启的新意图。
我创建了一个 MCVE 来说明这个问题:
Activity:
public class MainActivity extends ActionBarActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("MainActivity", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.intent_text);
}
@Override
protected void onResume() {
Log.d("MainActivity", "onResume");
super.onResume();
Intent intent = getIntent();
String text;
if (intent.hasExtra(Intent.EXTRA_TEXT)) {
text = intent.getExtras().getString(Intent.EXTRA_TEXT);
} else {
text = "nothing";
}
tv.setText(text);
}
}
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intenttest"
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="IntentTest"
android:theme="@style/Theme.AppCompat" >
<activity
android:name=".MainActivity"
android:label="IntentTest" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
</activity>
</application>
</manifest>
为了完整起见,简单的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.intenttest.MainActivity" >
<TextView
android:id="@+id/intent_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
- 启动应用,文本视图打印“无”
- 启动 YouTube 应用,共享链接,选择此应用,应用重新启动,文本视图显示 YouTube 共享的任何文本
- 新闻主页
- 返回 YouTube 应用,分享不同的链接,选择此应用,应用重新启动,文本视图显示与之前相同的旧文本
- 从“最近的应用”中按回或滑动应用
- 返回 YouTube 应用,分享另一个链接,选择此应用,应用重新启动(重新创建),文本视图显示 YouTube 刚刚分享的新文本
我觉得我在这里缺少一些基本的东西。如何让我的应用响应新的Intent?
【问题讨论】:
-
在 oncreate 之前尝试这个覆盖:@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent);设置意图(意图); }
-
onNewIntent()只有在活动设置为android:launchMode="singleTop"时才会被调用,正如 David Wasser 在他的回答中所描述的那样。
标签: android android-intent android-activity