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,如下所示 -

点击此处下载项目代码
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP