Play YouTube Videos in an Android App

移动开发 DZone

In this tutorial, we will learn how to play videos from a YouTube channel in an Android app using the YouTubePlayer API. We will get a channel’s video data in JSON format and parse it into a ListView.

1. Find YouTube Channel ID

Go to any YouTube channel’s homepage and copy the URL of that channel. If we copy the URL of Narendra Modi’s channel, the URL will look like this (the last word after channel/ is the channel id):

URL: https://www.youtube.com/channel/UC1NF71EwP41VdjAU1iXdLkw

Channel Id: UC1NF71EwP41VdjAU1iXdLkw

2. Generate SHA1 Key

When you signup for the YouTubePlayer API on the Google Developer console, you need to generate a SHA1 key. For this, follow these steps:

  1. Go to your Android Project and click on the Gradle icon.
  2. Click on YourProjectName(root) after that. If nothing is showing, click on the refresh icon.
  3. Now go to Tasks -> android -> signingReport. You will find the SHA1 key.

3. Get the API Key for YouTube Data API v3

Go to Google Developer Console and click on “select a project.” You can choose an existing project or create a new project for Youtube integration.

Search for Youtube Data API v3 choose this API and enable it. Now you will navigate to project dashboard.

Click on “Credentials” then “create credentials” and copy your API key and save it. You can restrict the key by choosing according to your usage and paste the SHA1 key that we generated in step 1 and save it. We are selecting “none,” however, it is always recommended to use restriction.

4. Get Channel Video List in JSON Format

Now go to the Youtube Data API docs and scroll down to find the Authorize and Execute button. For the sake of simplicity, we execute data in Load in APIs Explorer and we navigate to another page.

There are many parameters, but only the part parameter is mandatory. Now put the channel id that we got in the first step in the channelId text field. Hit the Authorize and Execute button. We will get videos list and descriptions of the channel in JSON. Copy the URL that we get from the GET request. You can run this URL in the browser as well by replacing {YOUR_API_KEY}.

Android Integration

We will use the Volley library to parse the JSON data and populate it into a ListView. We have to add it to our build.gradle file of the app.

Now download the YoutubeAndroidPlayerApi.jar file and copy this into the libs folder of your Android project. If the folder does not exist, create a libs folder.

5. Create ChannelActivity Activity

I named it activity_channel. In this activity, we are using ListView to show YouTube videos in a list. The XML code of this file is given below:


    
    

ChannelActivity.java

We are parsing JSON data and using a custom adapter to supply data in a ListView. You may get an error due to not getting classes; just leave that and follow the next steps to create classes.

package com.techiesatish.youtubeintegration;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class ChannelActivity extends AppCompatActivity {
    ListView lvVideo;
    ArrayList videoDetailsArrayList;
    CustomListAdapter customListAdapter;
    String searchName;
    String TAG="ChannelActivity";
    String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC9CYT9gSNLevX5ey2_6CK0Q&maxResults=25&key={Your API KEI}";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_channel);
        lvVideo=(ListView)findViewById(R.id.videoList);
        videoDetailsArrayList=new ArrayList();
        customListAdapter=new CustomListAdapter(ChannelActivity.this,videoDetailsArrayList);
                showVideo();

    }

    private void showVideo() {
        RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray jsonArray=jsonObject.getJSONArray("items");
                    for(int i=0;i<jsonarray.length();i++){ jsonobject="" jsonobject1="jsonArray.getJSONObject(i);" jsonvideoid="jsonObject1.getJSONObject("id");" jsonsnippet="jsonObject1.getJSONObject("snippet");" jsonobjectdefault="jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");" videodetails="" videodetails();="" string="" videoid="jsonVideoId.getString("videoId");" log.e(tag,"="" new="" video="" id"="" +videoid);="" videodetails.seturl(jsonobjectdefault.getstring("url"));="" videodetails.setvideoname(jsonsnippet.getstring("title"));="" videodetails.setvideodesc(jsonsnippet.getstring("description"));="" videodetails.setvideoid(videoid);="" videodetailsarraylist.add(videodetails);="" }="" lvvideo.setadapter(customlistadapter);="" customlistadapter.notifydatasetchanged();="" catch="" (jsonexception="" e)="" {="" e.printstacktrace();="" },="" response.errorlistener()="" @override="" public="" void="" onerrorresponse(volleyerror="" error)="" error.printstacktrace();="" });="" int="" sockettimeout="30000;" retrypolicy="" policy="new" defaultretrypolicy(sockettimeout,="" defaultretrypolicy.default_max_retries,="" defaultretrypolicy.default_backoff_mult);="" stringrequest.setretrypolicy(policy);="" requestqueue.add(stringrequest);="" } 
 

6. Create a CustomListAdapter Class

This class extends BaseAdapter and populates data in a ListView. The code is given below:

package com.techiesatish.youtubeintegration;

import android.support.v4.app.FragmentManager;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;

public class CustomListAdapter extends BaseAdapter {
    Activity activity;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    private LayoutInflater inflater;
    ArrayList singletons;

    public CustomListAdapter(Activity activity, ArrayList singletons) {
        this.activity = activity;
        this.singletons = singletons;
    }

    public int getCount() {
        return this.singletons.size();
    }

    public Object getItem(int i) {
        return this.singletons.get(i);
    }

    public long getItemId(int i) {
        return (long) i;
    }

    public View getView(int i, View convertView, ViewGroup viewGroup) {
        if (this.inflater == null) {
            this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
                   // getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if (convertView == null) {
            convertView = this.inflater.inflate(R.layout.videolist, null);
        }
        if (this.imageLoader == null) {
            this.imageLoader = AppController.getInstance().getImageLoader();
        }
        NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
        final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
        final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
        final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
        final  TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);


       ((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(view.getContext(), VideoActivity.class);
                intent.putExtra("videoId",tvVideoID.getText().toString());
                view.getContext().startActivity(intent);

            }
        });


        VideoDetails singleton = (VideoDetails) this.singletons.get(i);
        networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
        tvVideoID.setText(singleton.getVideoId());
        imgtitle.setText(singleton.getVideoName());
        imgdesc.setText(singleton.getVideoDesc());
        return convertView;
    }
}

7.Create an AppController Class

In this class, we are creating an AppController class which is extending the application. We also need to define it in the AndroidManifest file:

package com.techiesatish.youtubeintegration;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {
    public static final String TAG = AppController.class.getSimpleName();
    private static AppController mInstance;
    private ImageLoader mImageLoader;
    private RequestQueue mRequestQueue;

    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        AppController appController;
        synchronized (AppController.class) {
            appController = mInstance;
        }
        return appController;
    }

    public RequestQueue getRequestQueue() {
        if (this.mRequestQueue == null) {
            this.mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return this.mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (this.mImageLoader == null) {
            this.mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public  void addToRequestQueue(Request req, String tag) {
        if (TextUtils.isEmpty(tag)) {
            tag = TAG;
        }
        req.setTag(tag);
        getRequestQueue().add(req);
    }

    public  void addToRequestQueue(Request req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (this.mRequestQueue != null) {
            this.mRequestQueue.cancelAll(tag);
        }
    }
}

8. Create an LRUBitmapCache Class

By using the Volley library, downloading and caching of images is very simple. The code of this class is given below:

package com.techiesatish.youtubeintegration;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

public class LruBitmapCache extends LruCache implements ImageLoader.ImageCache {
    public static int getDefaultLruCacheSize() {
        return ((int) (Runtime.getRuntime().maxMemory() / 1024)) / 8;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    protected int sizeOf(String key, Bitmap value) {
        return (value.getRowBytes() * value.getHeight()) / 1024;
    }

    public Bitmap getBitmap(String url) {
        return (Bitmap) get(url);
    }

    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

9. Create a VideoDetails Class

In this class, we are using setter and getter methods to update and retrieve the values of videos.

package com.techiesatish.youtubeintegration;
public class VideoDetails {
    String VideoName;
    String VideoDesc;
    String URL;
    String VideoId;


public void setVideoName(String VideoName){
    this.VideoName=VideoName;
}

public String getVideoName(){
    return VideoName;
}

public void setVideoDesc(String VideoDesc){
    this.VideoDesc=VideoDesc;
}

public String getVideoDesc(){
    return VideoDesc;
}

public void setURL(String URL){
    this.URL=URL;
}

public String getURL(){
    return URL;
}

public void setVideoId(String VideoId){
    this.VideoId=VideoId;
}
public String getVideoId(){
    return VideoId;
}

}

10. Create a VideoActivity

We will create an activity to show YouTube videos. We are using YoutubePlayerView to show videos. This is the XML file of the activity:



    

VideoActivity.java

This activity extends YouTubeBaseActivity. In this activity, we are getting the video id from ChannelActivity and using the curVideo() method to show the video.

package com.techiesatish.youtubeintegration;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Config;
import android.util.Log;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
String API_KEY="Your API Key";
    private static final int RECOVERY_REQUEST = 1;
    String TAG="VideoActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
       youTubePlayerView=(YouTubePlayerView)findViewById(R.id.youtubeview);
       youTubePlayerView.initialize(API_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

        Bundle bundle = getIntent().getExtras();
        String showVideo = bundle.getString("videoId");
        Log.e(TAG,"Video" +showVideo);
        youTubePlayer.cueVideo(showVideo);

    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        if (youTubeInitializationResult.isUserRecoverableError()) {
            youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
        } else {

            Toast.makeText(this, "Error Intializing Youtube Player", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_REQUEST) {
            getYouTubePlayerProvider().initialize(API_KEY, this);
        }
    }

    protected YouTubePlayer.Provider getYouTubePlayerProvider() {
        return youTubePlayerView;
    }

}

11. Add Internet Permission and Define AppController in the Manifest File


    

    
        
            
                

                
            


        
        


        
    

Now run this app and enjoy! If you are facing any problems, let me know in the comments. I will be happy to help you. You can download this code from GitHub .

DZone稿源:DZone (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Play YouTube Videos in an Android App

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录