Hướng dẫn cách tích hợp youtube api v3 vào ứng dụng android

Xin chào các bạn, hôm nay mình xin hướng dẫn về cách hiển thị video Youtube lên ứng dụng Android, cách đăng ký và sử dụng Youtube API V3, cách parse json hiển thị video… .

1. ĐĂNG KÝ TÀI KHOẢN

Truy cập vào đường dẫn sau:  https://console.developers.google.com

Tiến hành tạo một project:

Sau khi khởi tạo thành công tiến hành bật Youtube data API v3 lên để sử dụng.

Tiến hành tạo một Credentials

Điền các thông tin để tạo key: Xem cách lấy mã SHA nhanh chóng

Tạo tiếp một Credentials đặt tên là BrowserKey

Oke vậy là chúng ta đã hoàn thành bước 1 và có trong tay 2 Key để sử dụng:

2. Import thư viện và demo load danh sách video

Đầu tiên tiến hành download và import thử viện youtube api vào ứng dụng.

Step 1:

Download  phiên bản Youtube Android API player mới nhất về :

https://developers.google.com/youtube/android/player/downloads/

Step 2:Giải nén và chỉ cần sử dụng file .jar trong thư mục libs copy file jar vào ứng dụng.

Mở build.gralde thêm 3 dòng này vào :

 compile files('libs/YouTubeAndroidPlayerApi.jar')
 compile 'com.android.support:recyclerview-v7:25.1.1'
 compile 'com.github.bumptech.glide:glide:3.7.0'

 

Vậy là xong bước 2 import lib.

3. Sử dụng API với Playlist trên youtube.

Step1 : Đầu tiên minh phải lấy được ID của playlist:

Vào 1 Playlist mà bạn muốn sử dụng. Tượng tự của ID video nó sẽ có dạng như thế này:

Step 2: Truy cập vào link https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list

Part:sẽ điền vào snippet để lấy thông tin của playlist

Playlistid: bỏ vào ID playlist mà mình tìm ở step 1

Excute: chạy.

Kết quả như sau:

Các bạn có thể xem thêm các api khác tại đây : https://developers.google.com/apis-explorer/#p/youtube/v3/

4. Tạo project parse data json

  • Tạo file item_videl.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img_thumnail"
        android:layout_width="150dp"
        android:layout_height="150dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/img_thumnail"
        android:paddingLeft="10dp"
        android:layout_toEndOf="@+id/img_thumnail"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tiêu đề Video"
            android:textSize="18dp"
            android:textColor="@android:color/holo_red_dark"
            android:id="@+id/tv_title" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"
            android:text="Mô Tả"
            android:id="@+id/tv_decription" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/black"/>

</RelativeLayout>
  • Tạo file Video.java lưu trữ dữ liệu
package com.lynkdev.youtubeapiv3.model;

import java.io.Serializable;

/**
 * Created by LynkMieu on 2/7/2017.
 */

public class Video implements Serializable {
    private String urlVideo;
    private String thumnail;
    private String title;
    private String decription;

    public Video() {
    }

    public Video(String urlVideo, String thumnail, String title, String decription) {
        this.urlVideo = urlVideo;
        this.thumnail = thumnail;
        this.title = title;
        this.decription = decription;
    }

    public String getUrlVideo() {
        return urlVideo;
    }

    public void setUrlVideo(String urlVideo) {
        this.urlVideo = urlVideo;
    }

    public String getThumnail() {
        return thumnail;
    }

    public void setThumnail(String thumnail) {
        this.thumnail = thumnail;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDecription() {
        return decription;
    }

    public void setDecription(String decription) {
        this.decription = decription;
    }
    
}
  • Tạo một YoutubeAdapter.java như sau:
public class YoutubeAdapter extends RecyclerView.Adapter<YoutubeAdapter.VideoHolder>{
    private Activity activity;
    private ArrayList<Video> listVideo;

    public YoutubeAdapter(Activity activity, ArrayList<Video> listVideo) {
        this.activity = activity;
        this.listVideo = listVideo;
    }

    @Override
    public VideoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_video,parent,false);
        return new VideoHolder(view);
    }

    @Override
    public void onBindViewHolder(VideoHolder holder, int position) {
        final Video video = listVideo.get(position);
        holder.tvTitle.setText(video.getTitle());
        holder.tvDecription.setText(video.getDecription());
        Glide.with(activity)
                .load(video.getThumnail())
                .centerCrop()
                .into(holder.imgThumnail);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("Video",video);
                Intent intent = new Intent(activity, PlayVideoYoutube.class);
                intent.putExtras(bundle);
                activity.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listVideo.size();
    }

    class VideoHolder extends RecyclerView.ViewHolder{
        ImageView imgThumnail;
        TextView tvTitle;
        TextView tvDecription;
        public VideoHolder(View itemView) {
            super(itemView);
            imgThumnail = (ImageView) itemView.findViewById(R.id.img_thumnail);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDecription = (TextView) itemView.findViewById(R.id.tv_decription);
        }
    }
}
  • Tại layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/recycler_video" />
</LinearLayout>
  • Code MainActivity.java sử dụng AsyncTask để parse json
public class MainActivity extends AppCompatActivity {
    String API_URI = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=";
    String PLAYLIST_ID = "PL0vwEzPOisip7ZyXyDv21iKsFvbMiVgLj";
    String KEY_BROWSE = "AIzaSyAoMvZHGPUU0mw3ic0IO8oHOQOAP4fxnVs";
    RecyclerView recyclerVideo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerVideo = (RecyclerView) findViewById(R.id.recycler_video);
        new ParseVideoYoutube().execute();
    }

    //Setup recyclerView
    private void setupRecyclerView(ArrayList<Video> listVideo) {
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        recyclerVideo.setHasFixedSize(true);
        recyclerVideo.setLayoutManager(manager);
        recyclerVideo.setItemAnimator(new DefaultItemAnimator());
        YoutubeAdapter adapter = new YoutubeAdapter(this,listVideo);
        recyclerVideo.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    //AsyncTask parse Json
    private class ParseVideoYoutube extends AsyncTask<Void, Void, ArrayList<Video>> {
        @Override
        protected ArrayList<Video> doInBackground(Void... params) {
            ArrayList<Video> listVideo = new ArrayList<>();
            URL jSonUrl;
            URLConnection jSonConnect;
            try {
                jSonUrl = new URL(API_URI + PLAYLIST_ID + "&key=" + KEY_BROWSE);
                jSonConnect = jSonUrl.openConnection();
                InputStream inputstream = jSonConnect.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream, "UTF-8"), 8);
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                }
                inputstream.close();
                String jSontxt = stringBuilder.toString();

                JSONObject jsonobject = new JSONObject(jSontxt);
                JSONArray allItem = jsonobject.getJSONArray("items");
                for (int i = 0; i < allItem.length(); i++) {
                    JSONObject item = allItem.getJSONObject(i);
                    JSONObject snippet = item.getJSONObject("snippet");
                    String title = snippet.getString("title");              // Get Title Video
                    String decription = snippet.getString("description");   // Get Description
                    JSONObject thumbnails = snippet.getJSONObject("thumbnails");    //Get Url Thumnail
                    JSONObject thumnailsIMG = thumbnails.getJSONObject("medium");
                    String thumnailurl = thumnailsIMG.getString("url");

                    JSONObject resourceId = snippet.getJSONObject("resourceId");    //Get ID Video
                    String videoId = resourceId.getString("videoId");

                    Video video = new Video();
                    video.setTitle(title);
                    video.setThumnail(thumnailurl);
                    video.setDecription(decription);
                    video.setUrlVideo(videoId);
                    //Add video to List
                    listVideo.add(video);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return listVideo;
        }

        @Override
        protected void onPostExecute(ArrayList<Video> videos) {
            super.onPostExecute(videos);
            setupRecyclerView(videos);
        }
    }

}
  • Tạo thêm 1 Activity dùng để play video có tên: PlayVideoYoutube.java
public class PlayVideoYoutube extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

    private static final String YOUTUBE_APP_KEY = "AIzaSyDE75Eu70EWa4iVTbzbAEMCDDrRbwcP9Rw";
    private String VIDEO_ID;
    private String TITLE_VIDEO;
    YouTubePlayerView youTubeView;
    TextView txtName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
        txtName = (TextView) findViewById(R.id.txtName);
        youTubeView.initialize(YOUTUBE_APP_KEY, PlayVideoYoutube.this);
        Bundle bundle = getIntent().getExtras();
        Video video = (Video) bundle.getSerializable("Video");
        TITLE_VIDEO = video.getTitle();
        txtName.setText(TITLE_VIDEO);
        VIDEO_ID = video.getUrlVideo();
        Toast.makeText(this, VIDEO_ID, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        if (!b) {
            youTubePlayer.setShowFullscreenButton(true);
            youTubePlayer.cueVideo(VIDEO_ID);
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        String error = "Không thể load video! Kiểm tra Internet và ứng dụng Youtube trên máy của bạn!";
        Toast.makeText(this, error, Toast.LENGTH_LONG).show();
    }
}

activity_play_video.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:textColor="@android:color/black"
        android:padding="20dp"
        android:id="@+id/txtName"
        android:fontFamily="serif"
        android:layout_gravity="center_horizontal" />

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

</LinearLayout>

Thêm permistion Internet

  <uses-permission android:name="android.permission.INTERNET" />

Vậy là xong tiến hành Build để kiểm tra.

Lưu ý: Trường hợp không play được video vui lòng cài thêm ứng dụng Youtube.
– Để lấy toàn bộ Video các bạn thêm maxreult vào link API nhé tối đa 1 lần là 50 video.

https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet&maxResults=10&playlistId=PL0vwEzPOisip7ZyXyDv21iKsFvbMiVgLj&_h=3&

Nguyễn Linh

Chia sẻ để cùng tiến bộ...