0

我正在尝试确定用户在单击我的应用程序中的方向按钮时选择了哪个应用程序。我想要默认选择器的“始终”和“仅一次”选项,但我需要知道用户被发送到哪个应用程序,这就是我发现自己创建自定义选择器的原因。我已经对 SO 进行了研究,并遇到了以下帖子:

自定义选择器让我知道用户选择了什么应用程序:https ://stackoverflow.com/a/23494967/3957979

ActionProvider(在我的情况下不起作用,因为这不是 MenuItem): https ://stackoverflow.com/a/23495696/3957979

任何人都知道如何做到这一点?如果有办法使用默认选择器并仍然确定用户选择的应用程序,请告诉我。否则,请告诉我是否有办法将“始终”和“仅一次”选项集成到自定义选择器中。

下面是我正在实现的代码:

public View onCreateView(...) {
    ...
    shiftActionButtonDirections.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = directions(mLatitude, mLongitude, location.getFullAddress());
            // Check if any apps can handle geo intent
            if (intent.resolveActivity(getAppContext().getPackageManager()) != null) {
                showChooser(intent, "Get Directions with...");
            } else {
                Toast.makeText(getAppContext(), R.string.error_maps, Toast.LENGTH_LONG).show();
            }
        }
    });
    ...
}

public Intent directions(String latitude, String longitude, String address) {
    String uri = String.format("geo:%s,%s?q=%s", latitude, longitude, Uri.encode(address));
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return i;
}

private void showChooser(@NonNull final Intent intent, String title) {
    final List<ResolveInfo> activities = getAppContext().getPackageManager().queryIntentActivities(intent, 0);

    List<String> appNames = new ArrayList<String>();
    for (ResolveInfo info : activities) {
        appNames.add(info.loadLabel(getAppContext().getPackageManager()).toString());
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(TextUtils.isEmpty(title) ? "With..." : title);
    builder.setItems(appNames.toArray(new CharSequence[appNames.size()]), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            Map<String, Object> properties = new HashMap<>();
            ResolveInfo info = activities.get(item);

            if (info.activityInfo.packageName.contains("google")) {
                // Google Maps was chosen
            } else {
                // Another app was chosen
            }

            // start the selected activity
            intent.setPackage(info.activityInfo.packageName);
            startActivity(intent);
        }
    });

    AlertDialog alert = builder.create();
    alert.show();
}
4

1 回答 1

2

如果有办法使用默认选择器并仍然确定用户选择的应用程序,请告诉我。

将您的设置minSdkVersion为 22,然后使用createChooser(). 请注意,这不允许您更改有关用户选择的任何内容(例如,替换为不同的Intent);它只是让你有机会找出选择。

或者,如果您不想将您的设置minSdkVersion为 22,请在 API 级别 22+ 设备上使用三参数风格createChooser(),并在较旧的设备上执行其他操作(自定义选择器,无需选择信息等)。

否则,请告诉我是否有办法将“始终”和“仅一次”选项集成到自定义选择器中。

不,那是不可能的。

于 2015-12-16T19:35:54.467 回答