首页 > 解决方案 > 使用 singleInstance 时在 android 上多次启动 share-activity:始终获取第一个 url

问题描述

我有一个 android 应用程序,我可以通过共享功能从浏览器中保存 url(我创建了第二个带有发送意图过滤器的共享活动)

我尝试将launchMode更改为所有四个不同的选项,如果在标准或顶部,它可以工作,但是对于每个共享,都会启动一个应用程序实例。

<activity android:name=".ShareActivity" android:launchMode="singleInstance">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/*" />
    </intent-filter>
</activity>
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

主活动显示所有现有记录,而共享活动获取给定的 url 并保存它,然后启动主活动:

/**
 * Handle share-intent
 */
 protected void shareIntent()
 {
    String url = intent.getStringExtra(Intent.EXTRA_TEXT);  <- This is always the same when shared multiple urls
    // Here save the url ecc, wich works, so omiting the code

    startActivity(new Intent(getApplicationContext(), MainActivity.class)); <-- This starts the main-activity after the url has been saved
 }

/**
 * Main onCreate method, this will be called the first time when sharing
 * @param savedInstanceState
 */
 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        this.shareIntent();
 }

 // This will be called when sharing multiple times
 @Override
 protected void onResume()
 {
     super.onResume();
     this.shareIntent();
 }

当我使用标准或 singleTop 启动模式时,URL 会正确保存,但每次启动新实例时。如果我使用 singleTask 或 -Instance,将只有一个 app-instance,但无论我分享多少次,url 始终是第一个。

提前致谢

[更新]:有效!我这样做了:

@Override
protected void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);
    setIntent(intent);
}

并从 oncreate 中删除了对 share-method 的调用(因为即使是第一次调用 onresume )。

标签: androidsingle-instanceshare-intent

解决方案


推荐阅读