Android YouTube 應用如何透過 Intent 播放影片


在某些情況下,我們應該從我們的應用程式中開啟 YouTube 應用程式以顯示某些特定影片。此示例演示了 Android YouTube 應用如何透過 Intent 播放影片。

步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/parent"
   xmlns:tools="http://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>

在上面的程式碼中,我們使用了文字檢視。當您點選文字檢視時,它將開啟 YouTube 應用程式。

步驟 3 - 將以下程式碼新增到 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) {
            Intent webIntent = new Intent(Intent.ACTION_VIEW,
            Uri.parse("https://www.youtube.com/watch?v=5X7WWVTrBvM"));
            try {
               MainActivity.this.startActivity(webIntent);
            } catch (ActivityNotFoundException ex) {
            }
         }
      });
   }
}

在上面的程式碼中,我們使用了文字檢視。當用戶點選文字檢視時,它將開啟 YouTube,如下所示 -

Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=5X7WWVTrBvM"));
try {
   MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}

讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您專案中的一個活動檔案,然後點選執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

在上面的螢幕中,它是初始螢幕,當用戶點選文字檢視時,它將開啟 YouTube,如下所示 -

點選此處下載專案程式碼

更新於: 2019-07-30

2K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.