我理解隐式/显式意图的原理,但我无法通过以下代码创建显式意图:
getActivity().startService(new Intent(PowerampAPI.ACTION_API_COMMAND)
.putExtra(PowerampAPI.COMMAND, PowerampAPI.Commands.OPEN_TO_PLAY)
.setData(PowerampAPI.ROOT_URI.buildUpon()
.appendEncodedPath("folder_playlist_entries")
.appendEncodedPath(playlist_id)
.appendEncodedPath("files")
.build()));
运行此代码会出现以下错误:
.IllegalArgumentException:Service Intent必须是显式的:Intent { ACT = com.maxmpz.audioplayer.API_COMMAND dat = content://com.maxmpz.audioplayer.data/folder_playlist_entries/5/files(has extras)}
问题:如何将其转化为明确的意图?
答案 0 :(得分:0)
我知道您正在尝试启动服务。如果是这种情况,则必须为新的Intent()提供两个参数,如下所示:
startService(new Intent(this, service.class));
这样的decleration为startService方法提供了明确的意图。
您可以在此链接中找到有关服务以及如何启动服务的信息:
答案 1 :(得分:0)
Intent i = new Intent("com.maxmpz.audioplayer");
i.putExtra(PowerampAPI.COMMAND, PowerampAPI.Commands.OPEN_TO_PLAY);
i.setData(PowerampAPI.ROOT_URI.buildUpon()
.appendEncodedPath("folder_playlist_entries")
.appendEncodedPath(playlist_id)
.appendEncodedPath("files")
.build());
startService(i);
答案 2 :(得分:0)
我找到了一段代码,将隐含意图转换为显式意图。资料来源:http://blog.android-develop.com/2014/10/android-l-api-21-javalangillegalargumen.html
Intent intent = new Intent(PowerampAPI.ACTION_API_COMMAND);
intent.putExtra(PowerampAPI.COMMAND, PowerampAPI.Commands.OPEN_TO_PLAY)
.setData(PowerampAPI.ROOT_URI.buildUpon()
.appendEncodedPath("playlists")
.appendEncodedPath(playlist_id)
.appendEncodedPath("files")
.build());
Intent explicit_intent = new Intent(createExplicitFromImplicitIntent(getActivity(), intent));
getActivity().startService(explicit_intent);
和
/***
* Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,
* "java.lang.IllegalArgumentException: Service Intent must be explicit"
*
* If you are using an implicit intent, and know only 1 target would answer this intent,
* This method will help you turn the implicit intent into the explicit form.
*
* Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466
* @param context
* @param implicitIntent - The original implicit intent
* @return Explicit Intent created from the implicit original intent
*/
public Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
// Retrieve all services that can match the given intent
PackageManager pm = getActivity().getPackageManager();
List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
// Make sure only one match was found
if (resolveInfo == null || resolveInfo.size() != 1) {
return null;
}
// Get component info and create ComponentName
ResolveInfo serviceInfo = resolveInfo.get(0);
String packageName = serviceInfo.serviceInfo.packageName;
String className = serviceInfo.serviceInfo.name;
ComponentName component = new ComponentName(packageName, className);
// Create a new intent. Use the old one for extras and such reuse
Intent explicitIntent = new Intent(implicitIntent);
// Set the component to be explicit
explicitIntent.setComponent(component);
return explicitIntent;
}