java - 处理 Lollipop 中隐含的 Intent future 弃用

标签 java android android-intent service intentfilter

为了将数据传输到其他应用程序,我一直在使用隐式 Intent ,如下例所示:

Intent intent = new Intent();
intent.setAction("com.example.OpenURL");
intent.putExtra("URL_TO_OPEN", url_string);
sendOrderedBroadcastAsUser(intent);

Intent intent = new Intent();
intent.setAction("com.example.CreateUser");
intent.putExtra("Username", uname_string);
intent.putExtra("Password", pw_string);
sendBroadcast(intent);

Intent intent = new Intent();
intent.setAction("com.example.BackupUserData");
intent.setData(file_uri);
intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
sendBroadcast(intent);

但在 Android 5.0 中不再推荐这种行为

http://developer.android.com/about/versions/android-5.0-changes.html

Binding to a Service

The Context.bindService() method now requires an explicit Intent, and throws an exception if given an implicit intent. To ensure your app is secure, use an explicit intent when starting or binding your Service, and do not declare intent filters for the service.

来自 android 源代码,更准确地说是“ContextImpl”类:

private void validateServiceIntent(Intent service) {
        if (service.getComponent() == null && service.getPackage() == null) {
            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
                IllegalArgumentException ex = new IllegalArgumentException(
                        "Service Intent must be explicit: " + service);
                throw ex;
            } else {
                Log.w(TAG, "Implicit intents with startService are not safe: " + service
                        + " " + Debug.getCallers(2, 3));
            }
        }
    }

我该如何处理?

最佳答案

是的,当在装有 Android 5.0 的设备上运行时,此代码将显示警告(如果您的应用程序的 targetSdkVersion 小于 21)或彻底崩溃(如果针对 Lollipop 本身)。检查source code for validateServiceIntent() in ContextImpl.java :

此代码很危险,因为它可能允许恶意接收者自行注册并拦截(或更改)这些调用。

最合理的选择可能是使用 Intent.setPackage() 指定您要调用的应用程序的包名称。 .以这种方式完成后, Intent 不再是隐含的,而且它会起作用。例如:

   intent.setPackage("com.example.app");

当然,如果接收器在您的应用程序中,则有更简单的选择(但从您对问题的描述来看,情况似乎并非如此)。

关于java - 处理 Lollipop 中隐含的 Intent future 弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27981246/

相关文章:

java - 为什么 Spring 登录表单不会显示登录失败的任何错误信息?

java - 即使 Android 上的内存非常低,垃圾收集器也不会运行

android - 如何更新异步任务中的进度条

android - 将 ArrayList<CustomObject> 传递给另一个 Activity ,得到 NullPointerException

java - JSF 聊天示例

java - Android - 将日期从一个 fragment 添加到另一个正在运行的 fragment

Java 循环故障排除

android - AppBarLayout fitSystemtWindows =“true"在 layout_height 为 wrap_content 时不起作用

android - 通过 Intent 传递 ArrayList

android - 在 Activity 之间传递 Drawable