Cha*_*tem 7 android android-intent android-activity
我有一个带有单个 TextView 的简单应用程序,它显示来自 ACTION_SEND 意图的纯文本。我的问题是,每次将某些文本共享给此应用程序时,都会创建一个新实例。在检查最近的应用程序时,我可以看到该应用程序的多个实例。我正在 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试摆弄清单中的 launchMode,但没有一个选项解决了这个问题。
编辑1:
这是我的清单文件:
<?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>
Run Code Online (Sandbox Code Playgroud)
通常,如果另一个应用程序启动您的Activity(例如通过 ACTION_SEND),您Activity将被启动到另一个应用程序的现有任务中。因此,如果您使用其他 5 个应用程序,并且每个应用程序都Activity使用 ACTION_SEND启动您的应用程序,那么您将拥有 5 个 实例Activity,每个实例都在一个单独的任务中。
如果您希望Activity自己在自己的任务中运行,而不是在其他应用程序的任务中运行,那么您需要在清单launchMode="singleTask"中的<activity>声明中为此指定Activity。然后,当另一个应用程序启动您的 时Activity,Activity将在单独的任务中启动。如果Activity该任务中已经有运行的实例,那么 Android 将不会创建 的新实例Activity,它只会调用onNewIntent()并传递Intent其他应用程序在调用中使用的startActivity()。
| 归档时间: |
|
| 查看次数: |
2831 次 |
| 最近记录: |