Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Playing a YouTube Video

Author: Marco Dinacci -- Published? true -- FormatLanguage: W

Problem:

You want to play a video from Youtube on your device

Solution:

Given a URI to play the video, create an ACTION_VIEW Intent with it and start a new Activity.

Discussion:

For this recipe to work the user needs the standard Youtube application installed on the device.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    String video_path = "http://www.youtube.com/watch?v=opZ69P-0Jbc";
    Uri uri = Uri.parse(video_path);
        
    // With this line the Youtube application, if installed, will launch immediately.
    // Without it you will be prompted with a list of the application to choose.
    uri = Uri.parse("vnd.youtube:"  + uri.getQueryParameter("v"));
        
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

The example uses a standard YouTube.com URL. The uri.getQueryParameter("v") is used to extract the video ID from the URI itself, in our example the ID is opZ69P-0Jbc.

No records found.