如何识别我的应用是否被用户设置为默认?

rbo*_*bot 2 android android-intent

一旦我的主屏幕应用程序'X'安装在设备上,当用户按下主页按钮时,系统会提示他使用默认操作 Android对话框在默认主页和我的X应用程序之间进行选择.

我的用例是继续提示用户 - 虽然不经常使用此默认操作对话框,直到他选择我的应用程序为默认值.

  1. 我可以使用ACTION_MAIN意图进行提示.
  2. 问题是我什么时候应该停止提示?
    我怎么知道我的X应用程序现在是默认的?

Jen*_*ens 7

假设您有一个应用程序X,其清单中包含以下声明

<activity android:name=".MyActivity"
       android:label="@string/app_name">
    <!-- filter: This activity can be the default view action for a row in
         RawContacts -->
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <data android:mimeType="vnd.android.cursor.item/raw_contact" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)

要检查此应用程序是否为"默认选项"(在此examepl中为任何内容),您只需:

/**
 * Returns true if the supplied component name is the preferred activity
 * for any action.
 * @param component The ComponentName of your Activity, e.g. 
 *    Activity#getComponentName().
 */
boolean isDefault(ComponentName component) {
    ArrayList<ComponentName> components = new ArrayList<ComponentName>();
    ArrayList<IntentFilter> filters = new ArrayList<IntentFilter>();
    getPackageManager().getPreferredActivities(filters, components, null);
    return components.contains(component);
}    
Run Code Online (Sandbox Code Playgroud)