ইন্টেন্ট দিয়ে YouTube অ্যাপ খোলা
অ্যান্ড্রয়েডে Intent.ACTION_VIEW ব্যবহার করে YouTube URL পাস করলে সিস্টেম YouTube অ্যাপ (যদি ইনস্টল থাকে) বা ব্রাউজার খোলে।
উদাহরণ
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
ধাপ ২: লেআউট XML (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>
ধাপ ৩: জাভা কোড (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) {
// YouTube ভিডিও URL
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) {
// YouTube অ্যাপ বা ব্রাউজার নেই
ex.printStackTrace();
}
}
});
}
}
YouTube URL ফরম্যাট
// স্ট্যান্ডার্ড ওয়াচ URL https://www.youtube.com/watch?v=VIDEO_ID // শর্ট URL https://youtu.be/VIDEO_ID // এম্বেড URL https://www.youtube.com/embed/VIDEO_ID // নির্দিষ্ট সময় থেকে শুরু https://www.youtube.com/watch?v=VIDEO_ID&t=30s
YouTube অ্যাপে সরাসরি খোলা (Package Name ব্যবহার করে)
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:VIDEO_ID"));
intent.setPackage("com.google.android.youtube");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// YouTube অ্যাপ ইনস্টল নেই, ব্রাউজার ফলব্যাক
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=VIDEO_ID")));
}
সেরা অনুশীলন
- সবসময়
try-catchব্যবহার করুনActivityNotFoundExceptionহ্যান্ডল করার জন্য - YouTube Data API ব্যবহার করে ভিডিও মেটাডেটা পেতে পারেন
- YouTube Player API ব্যবহার করে অ্যাপের ভিতরে ভিডিও প্লে করতে পারেন