when i click the button i start a activity for youtube video like this:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.开发者_StackOverflow社区com/watch?v=cxLG2wtE7TM")));
if i use this its redirect to the intent chooser to open that video url on browser or youtube app. how to select the default app as youtube programmatically?
my output should open that video directly on youtube player. how? any idea?
Asking for a specific Activity is risky, as YouTube may change their package name which will follow with your application breaking.
Also - there is no guarantee that the YT player is installed on all Android Devices.
To circumvent, here is a code that searches for a youtube activity. If it finds it, it returns an intent to use it directly, otherwise, it keeps a "generic" intent that will result in the system intent chooser to be displayed.
/**
* @param context
* @param url To display, such as http://www.youtube.com/watch?v=t_c6K1AnxAU
* @return an Intent to start the YouTube Viewer. If it is not found, will
* return a generic video-play intent, and system will display a
* chooser to ther user.
*/
public static Intent getYouTubeIntent(Context context, String url) {
Intent videoIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
final PackageManager pm = context.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(videoIntent, 0);
for (int i = 0; i < activityList.size(); i++) {
ResolveInfo app = activityList.get(i);
if (app.activityInfo.name.contains("youtube")) {
videoIntent.setClassName(app.activityInfo.packageName, app.activityInfo.name);
return videoIntent;
}
}
return videoIntent;
}
You are using a implicit intent, which can match more than one receiver, thus the chooser. You could try switch to an explicit intent model, if you can figure out how to target the youtube activity directly. See developer documentation on explicit vs. implicit intents.
However, it seems the reason for the intent chooser is to let each user decide for themselves which player to use. Is there a good reason you want to bypass this? What if someone has installed a different video player that they prefer?
Edit: To call an explicit intent, you need to know the name of the activity you are trying to start, and you pass additional details as extras i.e.:
Intent intent = new Intent(this, YouTubeViewerActivity.class);
intent.addExtra("URI", Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM"));
startActivity(intent);
However, I totally made up the fact that there is a YouTubeViewerActivity class. As I said, typically if you are asking some outside service, like the YouTube app, to perform an action you use the implicit intent model like you have, so the user has control over what application is used.
精彩评论