gpt4 book ai didi

android - 提示默认 Activity 而不实际打开 Activity

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:33 26 4
gpt4 key购买 nike

我需要为特定的 MIME 类型设置默认应用程序。我知道如何清除默认值,但我需要在不实际打开应用程序的情况下提示用户。

PackageManager p = mContext.getPackageManager();
ComponentName cN = new ComponentName(mContext, FakeDownloadActivity.class);
p.setComponentEnabledSetting(cN, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

Intent selector = new Intent(Intent.ACTION_DEFAULT);
selector.addCategory(Intent.CATEGORY_DEFAULT);
selector.setType(mimeType);
mContext.startActivity(selector);

p.setComponentEnabledSetting(cN, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

上面的代码启动 Activity 而不是仅选择默认 Activity 。它的工作原理是启用虚假 Activity 然后将其禁用。这会导致 Select Default App 对话框在下次调用时显示。我只想选择默认 Activity 。

最佳答案

您正在寻找的是一个ACTION_PICK_ACTIVITY Intent 。

首先,您创建一个 Intent 来定义应该有资格选择的应用,例如:

Intent mainIntent = new Intent(Intent.ACTION_DEFAULT, null);
mainIntent.addCategory(Intent.CATEGORY_DEFAULT);

然后,您创建 ACTION_PICK_ACTIVITY Intent ,并作为 Extra,传递您之前创建的主要 Intent

Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);

现在,您只需为此 Intent 开始一个结果 Activity :

startActivityForResult(pickIntent, 0);

并且将创建一个对话框,用户可以在其中选择一个应用程序,但是当单击时, Activity 不会启动,相反,它将保留在您的 Activity 中,并且函数 onActivityResult 将被调用与结果。所以你需要创建那个函数:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

//In data, you have all the information about the selected application
if (data != null) {
//You can launch the application that we just picked with startActivity(data);
//or explore the variable to get all the information than you want
}
}

看看 Intent 类。那里有关于包名称和将要启动的类的信息。

从现在开始,您需要的是将该包和类设置为 Intent 的默认值,或者您需要的任何其他内容。不利的一面是,您只能为自己的内部目的保存该信息,例如决定下次用户执行某些操作时启动哪个应用程序。您不能做的是修改系统设置来为给定的 Intent 设置默认 Activity 。实际上,the package manager has the addPreferredActivity方法,应该这样做,但自 API 级别 8 起已弃用,原因如下:

This is a protected API that should not have been available to third party applications. It is the platform's responsibility for assigning preferred activities and this cannot be directly modified. Add a new preferred activity mapping to the system. This will be used to automatically select the given activity component when Context.startActivity() finds multiple matching activities and also matches the given filter.

关于android - 提示默认 Activity 而不实际打开 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20953901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com