为了将数据传输到其他应用程序,我一直在使用隐式 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/