我有一个带有单个 TextView 的简单应用,它显示来自 ACTION_SEND Intent 的纯文本。我的问题是,每次将某些文本共享到此应用程序时,都会创建一个新实例。我可以在检查最近的应用程序时看到该应用程序的多个实例。我正在 API 23 上测试它。
这是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity.java", "onCreate");
((TextView) findViewById(R.id.temp_textview)).setText("Share text/links from other apps");
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
String action = intent.getAction();
intent.getFlags();
Log.d("onResume - intent: ",intent.toString());
String type = intent.getType();
TextView displayText = (TextView) findViewById(R.id.temp_textview);
if (Intent.ACTION_SEND.equals(action) && type!=null) {
Log.d("MainActivity.java", "Intent verified");
if ("text/plain".equals(type)) {
handleSendText(intent, displayText);
}
}
}
void handleSendText(Intent intent, TextView displayText) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.d("MainActivity.java", sharedText);
if (sharedText != null) {
displayText.setText(sharedText);
}
}
}
我尝试修改 list 中的 launchMode,但没有一个选项可以解决问题。
编辑 1:
这是我的 list 文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="chaitanya.im.example">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<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/plain" />
</intent-filter>
</activity>
</application>
</manifest>
最佳答案
通常,如果另一个应用程序启动您的 Activity
(例如,通过 ACTION_SEND),您的 Activity
将启动到另一个应用程序的现有任务中。因此,如果您使用其他 5 个应用程序,并且每个应用程序都会启动您的 Activity
使用 ACTION_SEND,您将拥有 5 个 Activity
实例,每个都在一个单独的任务中。
如果你想要你的 Activity
要在自己的任务中自行运行,而不是在其他应用程序的任务中运行,则需要指定 launchMode="singleTask"
在<activity>
在 list 中为此 Activity
声明.然后,当另一个应用启动您的 Activity
时, Activity
将在单独的任务中启动。如果已经有一个 Activity
的实例在该任务中运行,那么 Android 将不会创建 Activity
的新实例, 它只会调用 onNewIntent()
并交付 Intent
在调用 startActivity()
时使用的其他应用程序.
关于android - 从 Intent.createChooser() 启动时如何防止应用程序/Activity 的多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679848/