Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách mở YouTube app phát video từ Intent trên Android

Giới thiệu

Để mở ứng dụng YouTube phát video cụ thể từ app của bạn, sử dụng Intent.ACTION_VIEW với URL YouTube. Hệ thống sẽ tự động mở app YouTube nếu có cài đặt, hoặc trình duyệt web nếu không.

Ví dụ minh họa

Bước 1: Tạo project

Android Studio → File → New Project.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:id="@+id/openYoutube"
        android:text="Open youtube application"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Bước 3: Code (src/MainActivity.java)

package com.example.andy.myapplication;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView openYoutube = findViewById(R.id.openYoutube);
        openYoutube.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // URL video YouTube
                String videoUrl = "https://www.youtube.com/watch?v=5X7WWVTrBvM";
                
                Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(videoUrl));
                
                try {
                    startActivity(webIntent);
                } catch (ActivityNotFoundException ex) {
                    // Không có app nào xử lý được intent
                    ex.printStackTrace();
                }
            }
        });
    }
}

Các dạng URL YouTube hỗ trợ

Loại URL Mô tả
Video chuẩn https://www.youtube.com/watch?v=VIDEO_ID Phát video đơn lẻ
Playlist https://www.youtube.com/playlist?list=PLAYLIST_ID Mở playlist
Kênh https://www.youtube.com/channel/CHANNEL_ID Mở kênh
Shorts https://www.youtube.com/shorts/SHORTS_ID Mở YouTube Shorts
Deep link (app) vnd.youtube://VIDEO_ID Mở trực tiếp app YouTube (nếu cài)

Mở trực tiếp app YouTube (Deep Link)

// Chỉ mở app YouTube, không fallback về browser
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://5X7WWVTrBvM"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // YouTube app không cài đặt, fallback về web
    Intent webIntent = new Intent(Intent.ACTION_VIEW, 
        Uri.parse("https://www.youtube.com/watch?v=5X7WWVTrBvM"));
    startActivity(webIntent);
}

YouTube Data API (Nâng cao)

Nếu cần kiểm soát phát video (play, pause, seek, events), sử dụng YouTube Android Player API:

// build.gradle
implementation 'com.google.android.youtube.player:1.2.2'

// Layout
<com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_player"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

// Activity implements YouTubePlayer.OnInitializedListener
YouTubePlayerView playerView = findViewById(R.id.youtube_player);
playerView.initialize("YOUR_API_KEY", this);

Xử lý lỗi thường gặp

  • ActivityNotFoundException: Không có app YouTube, fallback về browser
  • Video không tồn tại: YouTube app sẽ hiển thị lỗi nội bộ
  • Network error: Xử lý bằng try-catch hoặc kiểm tra kết nối trước

Lưu ý

  • Không cần quyền đặc biệt cho Intent.ACTION_VIEW
  • Luôn xử lý ActivityNotFoundException
  • Deep link vnd.youtube:// chỉ hoạt động nếu YouTube app đã cài
  • URL youtu.be/VIDEO_ID cũng được hỗ trợ