Cách lấy API Youtube

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: //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ậtYoutube data API v3 lên để sử dụng.

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

Đ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ộtCredentials đặ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ề :

//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//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 ://developers.google.com/apis-explorer/#p/youtube/v3/

4. Tạo project parse data json

  • Tạo file item_videl.xml
  • 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{ private Activity activity; private ArrayList listVideo; public YoutubeAdapter[Activity activity, ArrayList 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
  • Code MainActivity.java sử dụng AsyncTask để parsejson
public class MainActivity extends AppCompatActivity { String API_URI = "//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 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 { @Override protected ArrayList doInBackground[Void... params] { ArrayList 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 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

Thêm permistion 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.

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

Video liên quan

Chủ Đề