+1

Cách tạo một ứng dụng chạy video trên Android application

Chào ace. Hôm nay tôi sẽ trình bày một chút hiểu biết mà tôi đã tìm hiểu được về làm thế nào để phát triển một ứng dụng về video trên android.

Có rất nhiều cách để phát triển một ứng dụng như vậy, hoặc là chạy trực tiếp video trên client(cái này mà chạy đến 2 cái video thì dung lượng ngập face), hoặc là chạy video từ một đường link mà bạn đã upload lên hosting của mình, hoặc là chạy video từ một hosting khác nhưng theo tôi cách hay nhất đó là chạy luôn các video từ kênh Youtube. Giảm thiểu được mọi chi phí, video load nhanh. Vì vậy trong bài này tôi chỉ tập trung vào cách để có thể tạo ra một ứng dụng chạy video youtube trên android.

Để làm được công việc trên thì trước hết chúng ta cần phải có một developer key để sử dụng Youtube API. Có thể đăng ký tại đây Google's YouTube Developer.

  1. Tạo project - android 1.JPG

  2. Tiếp theo chúng ta sẽ lấy các thư viện sau:

  • YouTube Android Player API: Thư viện này dùng cho việc nhúng và điều khiển các video Youtube, download tại đây.
  • YouTube Data API v3 Client Library for Java giúp truy vấn thông tin trên Youtube.
  • Picasso Giúp lấy và hiển thị hình ảnh từ xa.

Ok, sau khi đã lấy các thư viện về, copy YouTubeAndroidPlayerApi.jar, picasso..xxx.jar vào folder Libs. Giải nén google-api-services-youtube-v3-rev130-java-1.19.1.zip và cũng copy vào Libs.

Trong file AndroidManifest.xml nhớ thêm permission internet:

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

Ứng dụng của chúng ta có 2 activity nên định nghĩa luôn và ngay trong file xml:

<activity android:name=".MainActivity"
    android:screenOrientation="landscape">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>
<activity android:name=".PlayerActivity"
    android:screenOrientation="landscape" />

Thêm nội dung file string.xml như sau:

<resources>

    <string name="app_name">SimplePlayer</string>
    <string name="search">Search</string>

    <string name="failed">Failed to initialize Youtube Player</string>
      <string name="error_player">There was an error initializing the YouTubePlayer (%1$s)</string>
</resources>

Giờ chúng ta cùng tạo các layout: Đặt tên file xml thế nào tùy bạn nhé. Nội dung file activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/thumb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

</LinearLayout>

Thêm một layout activity_player.xml cho xem video:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

Một lớp lưu các biến static final như key api, key video test ...

package com.framgia.youtubeapi;

/**
 * Static container class for holding a reference to your YouTube Developer Key.
 */
public class DeveloperKey {
  public static final String DEVELOPER_KEY = "AIzaSyC5ameO6l8JqynlhcWFHC9v75mzgbyymkQ";

  public static final String KEY_VIDEO = "Kgqu-St99Po";
  public static final String TITLE_VIDEO = "Test Youtube API";
}

Tạo class YoutubeBaseActivity.java. Class này tôi lây từ google.

/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.framgia.youtubeapi;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.hathi.simpleplayer.R;

import android.content.Intent;
import android.widget.Toast;

/**
 * An abstract activity which deals with recovering from errors which may occur during API
 * initialization, but can be corrected through user action.
 */
public abstract class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

  private static final int RECOVERY_DIALOG_REQUEST = 1;

  @Override
  public void onInitializationFailure(YouTubePlayer.Provider provider,
      YouTubeInitializationResult errorReason) {
    if (errorReason.isUserRecoverableError()) {
      errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
    } else {
      String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
      Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_DIALOG_REQUEST) {
      // Retry initialization if user performed a recovery action
      getYouTubePlayerProvider().initialize(DeveloperKey.DEVELOPER_KEY, this);
    }
  }

  protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();

}

Ok, sắp xong. giờ chúng ta cùng code cho file MainActivity

package com.framgia.youtubeapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.framgia.youtubeapi.R;
import com.squareup.picasso.Picasso;

public class MainActivity extends Activity {

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

		ImageButton thub = (ImageButton)findViewById(R.id.thumb);
		TextView txtTitle = (TextView)findViewById(R.id.title);
		String url = "http://img.youtube.com/vi/"+DeveloperKey.KEY_VIDEO+"/default.jpg"; // Đây là cách lấy ảnh icon cho video đó. Sau đó hiển thị nó vào view bằng Picasso
		Picasso.with(MainActivity.this).load(url).into(thub);
		txtTitle.setText(DeveloperKey.TITLE_VIDEO);

		thub.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Khi click vào icon video thì sẽ hiện tới trang xem video
				Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
				startActivity(intent);
			}
		});
	}
}

Code tiếp file show video, ngắn thôi:

package com.framgia.youtubeapi;

import com.framgia.youtubeapi.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

import android.os.Bundle;

public class PlayerActivity extends YouTubeFailureRecoveryActivity {

	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_player);

	    YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.player_view);
	    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
	  }

	  @Override
	  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
	      boolean wasRestored) {
	    if (!wasRestored) {
	      player.cueVideo(DeveloperKey.KEY_VIDEO);
	    }
	  }

	  @Override
	  protected YouTubePlayer.Provider getYouTubePlayerProvider() {
	    return (YouTubePlayerView) findViewById(R.id.youtube_view);
	  }

	}

Đã xong, giờ đây bạn có thể chạy ngon lành bất cứ video nào. Hoặc bạn có thể tạo một listview để show thật nhiều danh sách các video và xem chúng. Nếu bạn chưa làm bao giờ thì từ bài viết này hy vọng bạn có thể phát triển cho mình những ý tưởng to lớn và táo bạo. Chúc bạn thành công.

Đây là file APK build cho bạn chạy thử.

Pass giải nén là: recruit.framgia.vn https://drive.google.com/file/d/0B7td9WR1ZtQ0QTdxd1dJLVhZR3c/view?usp=sharing



All rights reserved

Bình luận

Đăng nhập để bình luận
Avatar
@princetoad
thg 11 2, 2015 9:01 SA

e muốn viết theo cách chạy video từ một đường link mà bạn đã upload lên hosting của mình thì làm thế nào ạ :3

Avatar
@nguyen.van.tung
thg 11 8, 2015 8:37 CH

@Thắng Trần Các link youtube đều có dạng https://www.youtube.com/watch?v=wLyKGoCF5mE

Nếu dùng luôn ví dụ trên và muốn chạy video từ link đã upload lên host thì viết 1 hàm xử lý để lấy mỗi cái key của video. Chúc thành công !

Avatar
@mrcuong
thg 11 15, 2016 3:58 CH

AD có thể cho mình xin project được không,mình đang làm một ứng dụng xem youtube nhưng toàn hướng dẫn youtube api xem được một video thôi,ko show được list video,mình làm bằng androistudio Thanks AD

Avatar
@nguyen.van.tung
thg 11 17, 2016 7:17 SA

Chào @Nguyen Manh Cuong Để mai mình tìm lại cho. Ngày xưa làm 1 project có cả chạy list video rồi, nhưng không nhớ vứt ở phương trời nào nữa rồi. Ngày đó nghịch ngợm nên không vứt lên githup 😃

Avatar
@bangvn
thg 12 9, 2016 8:29 SA

Cảm ơn Ad rất nhiểu. Mình đang viết một app sử dụng tính năng này, nhưng vì mới bắt đầu học nên chưa rành lắm. Nhờ ad chỉ giáo luôn cách để hiển thị thêm các video khác trong một Playlist bằng cách dùng Lisview mà ad có nói đến được không? Cảm ơn rất nhiều.

Avatar
@bangvn
thg 12 9, 2016 8:29 SA

Cảm ơn Ad rất nhiểu. Mình đang viết một app sử dụng tính năng này, nhưng vì mới bắt đầu học nên chưa rành lắm. Nhờ ad chỉ giáo luôn cách để hiển thị thêm các video khác trong một Playlist bằng cách dùng Lisview mà ad có nói đến được không? Cảm ơn rất nhiều.

Avatar
@nguyen.van.tung
thg 12 12, 2016 9:10 CH

@bangvn @mrcuong Sory 2 bạn muốn hỏi tới phát 1 list của youtube hay là list mình tạo trên android vậy

Avatar
@tranlananh54
thg 4 15, 2017 2:22 CH

AD có em xin cái project tạo list youtube trên android studio với ạ, em đang làm đồ án tốt nghiệp cần mà ko làm được, cảm ơn ad nhiều

Avatar
@dungdmph05085
thg 3 31, 2018 2:20 SA

AD có thể cho mình xin project được không,mình đang làm một ứng dụng xem youtube dungdmph05085@fpt.edu.vn

Avatar
+1
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí