https://developers.google.com/youtube/v3/
2) After clicking on the above link click on Register your application
this will redirect you to a Google console page
Create a new project
a) Enter the name of your project and check the term and service box.
b) Click create after this it will ask to verify your account enter the SMS code
that you get via SMS
3) After verifying click on APIs under APIs and auth.
Turn ON the YouTube Analytics API and YouTube Data API v3
4) Now click on credentials
In public API access
Click create new key to generate the Android API key
For this open your cmd prompt change the location for your current directory to
C:\Program Files\Java\jdk1.6.0_16\bin> and type
keytool -v -list -alias androiddebugkey -keystore "Your debug key location" -storepass android
-keypass android
this will give you the SHA1 fingerprints copy the fingerprints and paste the fingerprints to the API
Console box with the package name of your project and click create.
5) Now copy the Android API key and save it to some Notepad.
5) Now copy the Android API key and save it to some Notepad.
6) Again go to the create new key and generate the Browser API key add some valid url and click
on create
copy the API key and save that key to some Notepad.
7) You Need to download the YouTubeAndroidPlayerApi.jar from this link https://github.com/youtube/yt-direct-lite-android download the Zip extract it and copy the jar from the lib folder to your project lib folder.
8) Now open eclipse create a new project Android Application Project enter the name of project
for example
Youtube and the package name com.example.youtube
click Next to enter the activity name for example MainActivity
and then click finish.
9) In activity_main.xml type the following code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/videolist"/>
</LinearLayout>
10) Right click on layout folder create new android xml file name it
a) textvideo.xml type the following code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/tumbhid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingLeft="4dp" />
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="118dp"
android:textColor="#5D2EE8"
android:textSize="20sp" >
</TextView>
</RelativeLayout>
b) full_screendemo.xml type the following code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/other_views"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="@android:color/black"
android:padding="5dp" >
<CheckBox
android:id="@+id/landscape_fullscreen_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@android:color/white"
android:text="@string/landscape_fullscreen" />
</LinearLayout>
</LinearLayout>
11) Navigate to Values folder open the Strings.xml file and add following values
<string name="error_player">There was an error initializing the YouTubePlayer</string>
<string name="landscape_fullscreen">Click on check for full screen video in landscape mode</string>
<string name="enter_fullscreen">Enter Fullscreen</string>
12) Navigate to source folder open the MainActivity.java and type this code
package com.example.youtube;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.youtube.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity implements OnItemClickListener{
private ArrayList<Video> videoArrayList;
private ListView listVideo;
private VideoAdapter videoAdapter;
private String auth_token;
private Video vObject;
private JsonParser parserVideo;
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listVideo=(ListView)findViewById(R.id.videolist);
parserVideo=new JsonParser();
getAuthToken();
videoArrayList=new ArrayList<Video>();
listVideo.setOnItemClickListener(this);
listVideo.setAdapter(videoAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// here we are getting the index of listview and through this we are getting the youtube video id
vObject=videoArrayList.get(position);
String video=vObject.getVideoId();
Intent inFullScreenDemo=new Intent(MainActivity.this,FullscreenDemoActivity.class);
inFullScreenDemo.putExtra("video",video);
inFullScreenDemo.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(inFullScreenDemo);
}
////This method is used to get the auth_token from your gmail sync account////
public void getAuthToken(){
AccountManager.get(getApplicationContext()).getAuthTokenByFeatures("com.google", "oauth2:https://gdata.youtube.com", null, this,
null, null, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
@SuppressWarnings("unused")
String acc_name = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.e("auth_token",auth_token);
} catch (Exception e) {
e.printStackTrace();
}
}
}, null);
new Async().execute("");
}
public ArrayList<Video>parsingJson(String videoUrl){
try {
JSONObject json=parserVideo.getJsonFromYoutube(videoUrl+auth_token);
JSONArray jArray=new JSONArray(json.getString("items"));
for(int i=0;i<jArray.length();i++){
JSONObject thumbnail=jArray.getJSONObject(i);
JSONObject snippets=thumbnail.getJSONObject("snippet");
JSONObject defaulturl=snippets.getJSONObject("thumbnails");
JSONObject url=defaulturl.getJSONObject("high");
JSONObject resourceId=snippets.getJSONObject("resourceId");
String videoId=resourceId.getString("videoId");
String imageurl=url.getString("url");
String title=snippets.getString("title");
vObject=new Video(title, imageurl, videoId);
videoArrayList.add(i,vObject);
//Log.e("videoArrayList",""+videoArrayList.size());
}
} catch (Exception e) {
e.printStackTrace();
}
return videoArrayList;
}
public void invalidateAccount(){
AccountManager accountManager = AccountManager.get(MainActivity.this);
accountManager.invalidateAuthToken("com.google",auth_token);
}
///This class is used to do some background task.
//Here in this blog, we are using it for parsing the JSON data
//that we are getting from youtube.
public class Async extends AsyncTask<String,String,String>{
ArrayList<Video> videolist;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress=new ProgressDialog(MainActivity.this);
progress.setMessage("Loading data...");
progress.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
videolist=parsingJson(parserVideo.url); //through this method we are parsing the data
}catch (Exception e) {
// TODO: handle exception
finish(); //If some exception occur we are killing the application
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
//videoAdapter class is used to customized the ListView
videoAdapter=new VideoAdapter(MainActivity.this,videolist,MainActivity.this.getContentResolver(),MainActivity.this.getResources());
listVideo.setAdapter(videoAdapter);
listVideo.setFastScrollEnabled(true);
progress.dismiss(); // Here we are closing the progress dialog after completing the background task.
}catch (Exception e) {
// TODO: handle exception
}
}
}
}
13) Right Click to com.example.youtube create new java class name it Video.java and type this code
package com.example.youtube;
public class Video {
private String videoTitle;
private String videoThumbnail;
private String videoId;
public String getVideoTitle() {
return videoTitle;
}
public void setVideoTitle(String videoTitle) {
this.videoTitle = videoTitle;
}
public String getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(String videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public Video(String videoTitle, String videoThumbnail, String videoId) {
super();
this.videoTitle = videoTitle;
this.videoThumbnail = videoThumbnail;
this.videoId = videoId;
}
public Video() {
super();
}
@Override
public String toString() {
return "Video [videoTitle=" + videoTitle + ", videoThumbnail="
+ videoThumbnail + ", videoId=" + videoId + "]";
}
}
14) Right Click to com.example.youtube create new java class name it VideoAdapter.java
and in Superclass tab type android.widget.ArrayAdapter
package com.example.youtube;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import com.example.youtube.R;
import com.example.loadimage.ImageLoader;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
public class VideoAdapter extends ArrayAdapter<Video> implements SectionIndexer {
@SuppressWarnings("unused")
private final Context context;
private final ArrayList<Video> itemsArrayList;
ContentResolver resolver;
Resources resource;
HashMap<String, Integer> alphaIndexer;
String[] sections;
private ImageLoader imgLoader;
public VideoAdapter(Context context, ArrayList<Video> itemsArrayList,ContentResolver resolver,Resources resource) {
super(context, R.layout.textvideo, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
this.resolver=resolver;
this.resource=resource;
alphaIndexer = new HashMap<String, Integer>();
int size = itemsArrayList.size();
for (int x = 0; x < size; x++) {
Video s = itemsArrayList.get(x);
// get the first letter of the store
String ch = s.getVideoTitle().substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();
// put only if the key does not exist
if (!alphaIndexer.containsKey(ch))
alphaIndexer.put(ch, x);
}
imgLoader = new ImageLoader(context);
Set<String> sectionLetters = alphaIndexer.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<String>(
sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sections = sectionList.toArray(sections);
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout alertView;
//Get the current alert object
// alerts al = getItem(position);
//Inflate the view
if(convertView==null)
{
alertView = new RelativeLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(R.layout.textvideo, alertView, true);
}
else
{
alertView = (RelativeLayout) convertView;
}
ImageView image=(ImageView)alertView.findViewById(R.id.tumbhid);
TextView labelView = (TextView) alertView.findViewById(R.id.label);
imgLoader.DisplayImage(itemsArrayList.get(position).getVideoThumbnail(), R.drawable.ic_launcher, image);
labelView.setText(itemsArrayList.get(position).getVideoTitle());
return alertView;
}
@Override
public int getPositionForSection(int section) {
// TODO Auto-generated method stub
return alphaIndexer.get(sections[section]);
}
@Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object[] getSections() {
// TODO Auto-generated method stub
return sections;
}
}
15) Right Click to com.example.youtube create new java class name it JsonParser.java
and type this code
package com.example.youtube;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.util.Log;
public class JsonParser {
public String url="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=30&playlistId=PLuwvwpFd3r9VCVeEymYcRqmoPVFzJjhZJ&fields=items(contentDetails%2Cetag%2Cid%2Csnippet)%2CnextPageToken&key="ENTER Your Browser API KEY"&access_token=";
//You can change the playlistId
//You can change the maxResults from 30 to 50 only videos can be fetched at a time
//For more detail go to this link https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it
private static StringBuilder sb;
private JSONObject jObj;
public JsonParser() {
// TODO Auto-generated constructor stub
}
public JSONObject getJsonFromYoutube(String url){
DefaultHttpClient httpclient = new DefaultHttpClient();
Log.e("url",url);
HttpGet getRequest = new HttpGet(url);
getRequest.setHeader("Accept", "application/json");
// Use GZIP encoding
getRequest.setHeader("Accept-Encoding", "gzip"); //
try {
HttpResponse response = (HttpResponse) httpclient
.execute(getRequest);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String result = readStream(instream);
Log.i("JSON", result);
instream.close();
jObj = new JSONObject(result);
}
} catch (Exception e) {
e.printStackTrace();
}
return jObj;
}
private static String readStream(InputStream is) {
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return sb.toString();
}
}
16) Right Click to com.example.youtube create new java class name it DeveloperKey.java and type this code
// Copyright 2012 Google Inc. All Rights Reserved.
package com.example.youtube;
/**
* Static container class for holding a reference to your YouTube Developer Key.
*/
public class DeveloperKey {
/**
* Please replace this with a valid API key which is enabled for the
* YouTube Data API v3 service. Go to the
* <a href="https://code.google.com/apis/console/">Google APIs Console</a> to
* register a new developer key.
*/
public static final String DEVELOPER_KEY = "Enter your Android API KEY";
}
17) Right Click to com.example.youtube create new java class name it FullscreenDemoActivity.java and type this code
/*
* 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.example.youtube;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import com.example.youtube.R;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
/**
* Sample activity showing how to properly enable custom fullscreen behavior.
* <p>
* This is the preferred way of handling fullscreen because the default fullscreen implementation
* will cause re-buffering of the video.
*/
public class FullscreenDemoActivity extends YouTubeFailureRecoveryActivity implements
View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
YouTubePlayer.OnFullscreenListener {
private static final int PORTRAIT_ORIENTATION = Build.VERSION.SDK_INT < 9
? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
private LinearLayout baseLayout;
private YouTubePlayerView playerView;
private YouTubePlayer player;
// private Button fullscreenButton;
private CompoundButton checkbox;
private View otherViews;
private boolean fullscreen;
private String videoid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.fullscreen_demo);
baseLayout = (LinearLayout) findViewById(R.id.layout);
playerView = (YouTubePlayerView) findViewById(R.id.player);
// fullscreenButton = (Button) findViewById(R.id.fullscreen_button);
checkbox = (CompoundButton) findViewById(R.id.landscape_fullscreen_checkbox);
otherViews = findViewById(R.id.other_views);
Intent intent=getIntent();
videoid=intent.getStringExtra("video");
checkbox.setOnCheckedChangeListener(this);
// You can use your own button to switch to fullscreen too
// fullscreenButton.setOnClickListener(this);
playerView.initialize(DeveloperKey.DEVELOPER_KEY, this);
doLayout();
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
setControlsEnabled();
// Specify that we want to handle fullscreen behavior ourselves.
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
player.setOnFullscreenListener(this);
if (!wasRestored) {
player.cueVideo(videoid);
}
}
@Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return playerView;
}
@Override
public void onClick(View v) {
// player.setFullscreen(!fullscreen);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int controlFlags = player.getFullscreenControlFlags();
if (isChecked) {
// If you use the FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE, your activity's normal UI
// should never be laid out in landscape mode (since the video will be fullscreen whenever the
// activity is in landscape orientation). Therefore you should set the activity's requested
// orientation to portrait. Typically you would do this in your AndroidManifest.xml, we do it
// programmatically here since this activity demos fullscreen behavior both with and without
// this flag).
setRequestedOrientation(PORTRAIT_ORIENTATION);
controlFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
controlFlags &= ~YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
}
player.setFullscreenControlFlags(controlFlags);
}
private void doLayout() {
LinearLayout.LayoutParams playerParams =
(LinearLayout.LayoutParams) playerView.getLayoutParams();
if (fullscreen) {
// When in fullscreen, the visibility of all other views than the player should be set to
// GONE and the player should be laid out across the whole screen.
playerParams.width = LayoutParams.MATCH_PARENT;
playerParams.height = LayoutParams.MATCH_PARENT;
otherViews.setVisibility(View.GONE);
} else {
// This layout is up to you - this is just a simple example (vertically stacked boxes in
// portrait, horizontally stacked in landscape).
otherViews.setVisibility(View.VISIBLE);
ViewGroup.LayoutParams otherViewsParams = otherViews.getLayoutParams();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
playerParams.width = otherViewsParams.width = 0;
playerParams.height = WRAP_CONTENT;
otherViewsParams.height = MATCH_PARENT;
playerParams.weight = 1;
baseLayout.setOrientation(LinearLayout.HORIZONTAL);
} else {
playerParams.width = otherViewsParams.width = MATCH_PARENT;
playerParams.height = WRAP_CONTENT;
playerParams.weight = 0;
otherViewsParams.height = 0;
baseLayout.setOrientation(LinearLayout.VERTICAL);
}
setControlsEnabled();
}
}
private void setControlsEnabled() {
checkbox.setEnabled(player != null
&& getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
// fullscreenButton.setEnabled(player != null);
}
@Override
public void onFullscreen(boolean isFullscreen) {
fullscreen = isFullscreen;
doLayout();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
doLayout();
}
}
18)Right Click to com.example.youtube create new java class name it YouTubeFailureRecoveryActivity.java and type this code
/*
* 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.example.youtube;
import com.example.youtube.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
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();
}
19) Right click to source folder,Create new package name it com.example.loadimage
Create new class in this package name it as ImageLoader.java
// This class is used to cache the image
package com.example.loadimage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.HttpsURLConnection;
import com.example.youtube.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
int stub_id = R.drawable.ic_launcher;
public void DisplayImage(String url, int loader, ImageView imageView)
{
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(loader);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Log.e("urll",""+url.toString());
Bitmap bitmap=null;
URL imageUrl = new URL(url.toString());
HttpsURLConnection conn = (HttpsURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
@SuppressWarnings("static-access")
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=2;
Bitmap b=BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
return b.createScaledBitmap(b,80, 60,true);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
20) Create new class in the above package (com.example.loadimage) name it as FileCache.java
package com.example.loadimage;
import java.io.File;
import android.content.Context;
public class FileCache {
private File cacheDir;
public FileCache(Context context){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"youtubeimage");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
21) Create new class in the above package (com.example.loadimage) name it as MemoryCache.java
package com.example.loadimage;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;
public class MemoryCache {
private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
public Bitmap get(String id){
if(!cache.containsKey(id))
return null;
SoftReference<Bitmap> ref=cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap){
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
public void clear() {
cache.clear();
}
}
22) Create new class in the above package (com.example.loadimage) name it as Utils.java
package com.example.loadimage;
import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
23) Open AndroidManifest.xml and type this code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.youtube"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCOUNT_MANAGER" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.youtube.MainActivity"
android:label="@string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.youtube.FullscreenDemoActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="sensor" >
</activity>
</application>
</manifest>
24) Your done now compile your project and run it.
source: http://androidapphive.blogspot.com/2014/01/how-to-download-playlist-from-youtube.html?showComment=1417574476322#c3839339079216541634
0 comments:
Post a Comment