【问题标题】:Android: How to switch to an existed activity?Android:如何切换到现有活动?
【发布时间】:2020-01-15 19:41:27
【问题描述】:

我正在编写一个文本编辑器,我正在使用

<activity android:name=".Editor">
    <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.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="file"/>
        <data android:scheme="content"/>
        <data android:scheme="http"/>
        <data android:scheme="https"/>
        <data android:mimeType="*/*"/>
    </intent-filter>
</activity>

AndroidManifest.xml 让我的编辑器可以从其他应用程序打开文件(例如,默认文件浏览器)。但是每次我从其他应用程序打开一个文件时,我的编辑器都会创建一个新的Editor 活动,这导致我的编辑器会有很多视图,我需要退出很多次。

所以我在想,在setContentView 之前创建一个新的Editor 活动时,检查是否存在另一个Editor 活动。如果存在,切换到另一个Editor活动并销毁当前活动:

public class Editor extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if () {// TODO if exists another Editor
            ;// TODO destroy current Editor
            ;// TODO switch to another Editor
        } else {
            setContentView(...);
            ...
        }
    }
}

如果可行,方法如何实现?

(因为我对java/xml不熟悉,所以不知道这个问题是否可以通过编辑AndroidManifest.xml的代码来解决。)

【问题讨论】:

    标签: android android-layout android-intent android-activity


    【解决方案1】:

    android:launchMode="singleTask" 添加到您的活动中,如下所示。此行确保您的活动只有一个实例(最新创建的实例)。添加此代码后,您可以删除 if/else 签入您的 Activity。

    <activity android:name=".Editor"
              android:launchMode="singleTask">
        <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.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="file"/>
            <data android:scheme="content"/>
            <data android:scheme="http"/>
            <data android:scheme="https"/>
            <data android:mimeType="*/*"/>
        </intent-filter>
    </activity>
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2019-01-13
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多