[android] Android YouTube app Play Video Intent

I have created a app where you can download YouTube videos for android. Now, I want it so that if you play a video in the YouTube native app you can download it too. To do this, I need to know the Intent that the YouTube native app puts out in order to play the YouTube app.
I could do this easially if I had the YouTube program on my emulator, so my 1st question is:
1. Can I download the YouTube app for my emulator, or...
2. What is the intent used when the user selects a video for playback.

This question is related to android youtube android-intent emulation

The answer is


Try this:

public class abc extends Activity implements OnPreparedListener{

  /** Called when the activity is first created. */

  @Override
    public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM")));          


    @Override
      public void onPrepared(MediaPlayer mp) {
        // TODO Auto-generated method stub

    }
  }
}

EDIT: The below implementation proved to have problems on at least some HTC devices (they crashed). For that reason I don't use setclassname and stick with the action chooser menu. I strongly discourage using my old implementation.

Following is the old implementation:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(youtubelink));
if(Utility.isAppInstalled("com.google.android.youtube", getActivity())) {
    intent.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
}
startActivity(intent);

Where Utility is my own personal utility class with following methode:

public static boolean isAppInstalled(String uri, Context context) {
    PackageManager pm = context.getPackageManager();
    boolean installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        installed = false;
    }
    return installed;
}

First I check if youtube is installed, if it is installed, I tell android which package I prefer to open my intent.


Here's how I solved this issue:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + video_id));
startActivity(intent);

Now that I've done some more research, it looks like I only needed 'vnd.youtube:VIDEO_ID' instead of two slashes after the colon (':' vs. '://'):

http://it-ride.blogspot.com/2010/04/android-youtube-intent.html

I tried most of the suggestions here and they didn't really work very well with all of the supposed "direct" methods raising exceptions. I would assume that, with my method, if the YouTube app is NOT installed, the OS has a default fallback position of something other than crashing the app. The app is theoretically only going on devices with the YouTube app on them anyway, so this should be a non-issue.


This will work if youtube app installed. If not, a chooser will show up to select other application:

Uri uri = Uri.parse( "https://www.youtube.com/watch?v=bESGLojNYSo" );
uri = Uri.parse( "vnd.youtube:" + uri.getQueryParameter( "v" ) );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );

/**
 * Intent to open a YouTube Video
 * 
 * @param pm
 *            The {@link PackageManager}.
 * @param url
 *            The URL or YouTube video ID.
 * @return the intent to open the YouTube app or Web Browser to play the video
 */
public static Intent newYouTubeIntent(PackageManager pm, String url) {
    Intent intent;
    if (url.length() == 11) {
        // youtube video id
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
    } else {
        // url to video
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    }
    try {
        if (pm.getPackageInfo("com.google.android.youtube", 0) != null) {
            intent.setPackage("com.google.android.youtube");
        }
    } catch (NameNotFoundException e) {
    }
    return intent;
}

You can also just grab the WebViewClient

wvClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
  if (url.startsWith("youtube:")) {
    String youtubeUrl = "http://www.youtube.com/watch?v="
    + url.Replace("youtube:", "");
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youtubeUrl)));
}
return false;
}

Worked fine in my app.


Youtube now has a player api, You should try that.

https://developers.google.com/youtube/android/player/


This function work fine for me...just pass url string in function:

void watch_video(String url)
{
    Intent yt_play = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
    Intent chooser = Intent.createChooser(yt_play , "Open With");

    if (yt_play .resolveActivity(getPackageManager()) != null) {
                    startActivity(chooser);
                }
}

Replying to old question, just to inform you guys that package have changed, heres the update

Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData("VALID YOUTUBE LINK WITH HTTP");
videoClient.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
startActivity(videoClient);

This works very well, but when you call normal Intent with ACTION_VIEW with valid youtube URL user gets the Activity selector anyways.


And how about this:

public static void watchYoutubeVideo(Context context, String id){
    Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
    Intent webIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://www.youtube.com/watch?v=" + id));
    try {
        context.startActivity(appIntent);
    } catch (ActivityNotFoundException ex) {
        context.startActivity(webIntent);
    }
} 

Note: Beware when you are using this method, YouTube may suspend your channel due to spam, this happened two times with me


The Youtube (and Market application) are only supposed to be used with special ROMs, which Google released for the G1 and the G2. So you can't run them in an OpenSource-ROM, like the one used in the Emulator, unfortunately. Well, maybe you can, but not in an officially supported way.


Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData(Uri.parse("http://m.youtube.com/watch?v="+videoId));
startActivityForResult(videoClient, 1234);

Where videoId is the video id of the youtube video that has to be played. This code works fine on Motorola Milestone.

But basically what we can do is to check for what activity is loaded when you start the Youtube app and accordingly substitute for the packageName and the className.


You can use the Youtube Android player API to play the video if Youtube app is installed, otherwise just prompt the user to choose from the available web browsers.

if(YouTubeIntents.canResolvePlayVideoIntent(mContext)){
                    mContext.startActivity(YouTubeIntents.createPlayVideoIntent(mContext, mVideoId));
}else {
    Intent webIntent = new Intent(Intent.ACTION_VIEW, 
           Uri.parse("http://www.youtube.com/watch?v=" + mVideoId));

    mContext.startActivity(webIntent);
}

This will work on a device but not the emulator per Lemmy's answer.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM")));

Use my code .. I am able to play youtube video using this code ... you just need to provide youtube video id in the "videoId" variable ....

String videoId = "Fee5vbFLYM4";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId)); 
intent.putExtra("VIDEO_ID", videoId); 
startActivity(intent); 

Found it:

03-18 12:40:02.842: INFO/ActivityManager(68): Starting activity: Intent { action=android.intent.action.VIEW data=(URL TO A FLV FILE OF THE VIDEO) type=video/* comp={com.google.android.youtube/com.google.android.youtube.YouTubePlayer} (has extras) }

Try this,

WebView webview = new WebView(this); 

String htmlString = 
    "<html> <body> <embed src=\"youtube link\"; type=application/x-shockwave-flash width="+widthOfDevice+" height="+heightOfDevice+"> </embed> </body> </html>";

webview.loadData(htmlString ,"text/html", "UTF-8");

The safest way to run videos on a different app is by first trying to resolve the package, in other words, check that the app is installed on the device. So if you want to run a video on youtube you'd do something like this:

public void playVideo(String key){

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + key));

    // Check if the youtube app exists on the device
    if (intent.resolveActivity(getPackageManager()) == null) {
        // If the youtube app doesn't exist, then use the browser
        intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://www.youtube.com/watch?v=" + key));
    }

    startActivity(intent);
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to youtube

Youtube - downloading a playlist - youtube-dl YouTube Autoplay not working How to embed new Youtube's live video permanent URL? How do you use youtube-dl to download live streams (that are live)? How can I get the actual video URL of a YouTube live stream? YouTube: How to present embed video with sound muted ffprobe or avprobe not found. Please install one Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to emulation

Waiting for Target Device to Come Online Android emulator not able to access the internet Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled Google Play Services Missing in Emulator (Android 4.4.2) Is there a real solution to debug cordova apps Genymotion Android emulator - adb access? How to get the sign, mantissa and exponent of a floating point number Simulate user input in bash script Enabling WiFi on Android Emulator How do I rotate the Android emulator display?