2011-09-20 70 views
5

我有一個GDATA鏈接,我想在我的應用程序中使用。此鏈接包含播放列表,我希望該播放列表在ListView中顯示。然後,用戶將選擇他/她想要的視頻,然後使用本地Youtube應用程序在應用程序旁邊播放。Youtube播放列表顯示在ListView中

請給我一個直觀的教程。我知道YouTube API頁面包含所有信息,但我可以對其進行正面或反面的描述。

回答

1

我希望這會給你一個想法嘗試這個(只是一個例子),如果你有更好的解決方案請讓我知道。

package com.test.utubevdo; 

    import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 
    import java.net.HttpURLConnection; 
    import java.net.MalformedURLException; 
    import java.net.URL; 
    import java.util.ArrayList; 

    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpGet; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONArray; 
    import org.json.JSONObject; 

    import android.app.Activity; 
    import android.app.Dialog; 
    import android.app.ListActivity; 
    import android.app.ProgressDialog; 
    import android.content.Intent; 
    import android.graphics.Bitmap; 
    import android.graphics.BitmapFactory; 
    import android.os.AsyncTask; 
    import android.os.Bundle; 
    import android.os.Handler; 
    import android.os.Message; 
    import android.view.ContextMenu; 
    import android.view.ContextMenu.ContextMenuInfo; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.view.WindowManager; 
    import android.widget.AdapterView; 
    import android.widget.AdapterView.OnItemClickListener; 
    import android.widget.Button; 
    import android.widget.Gallery; 
    import android.widget.ListView; 
    import android.widget.VideoView; 


    public class AndroidThumbnailList extends Activity{ 
     ArrayList <YTBVideo> videos = new ArrayList<YTBVideo>(); 

    ProgressDialog progressDialog = null; 
    VideoView vdovw_1 = null; 
    String vdoURL = ""; 
    ListView listview = null; 
    Gallery gallery = null; 
    Dialog noDataAlert = null; 


    Handler imageLoaderHandler = new Handler() { 
     public void handleMessage(final Message msg) { 
      progressDialog.dismiss(); 
      if(msg.what == 1){ 

       showErrorMessage("Communication Error", "Error Occured while retrieving the data from Youtube.\n Please try again"); 

      }else{ 
      System.out.println("videos ::"+videos.size()); 
      //listview.setAdapter(new VideoViewAdapter(AndroidThumbnailList.this, videos)); 
      gallery.setAdapter(new VideoViewAdapter1(AndroidThumbnailList.this, videos)); 
      } 

     } 
    }; 



    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 


     getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 

     //setContentView(R.layout.imagelist_layout); 
     //listview = (ListView)findViewById(R.id.listView1); 
     setContentView(R.layout.gallery_imagelist_layout); 
     gallery = (Gallery) findViewById(R.id.galleryView); 

     gallery.setOnItemClickListener(new OnItemClickListener() { 
       public void onItemClick(AdapterView parent, View view, int position, long id) { 
        Intent videoDisplayIntent = new Intent("com.test.utubevdo.VIEW_VIDEO"); 
        System.out.println("String.valueOf(view.getTag()) :::"+((YTBVideo)videos.get(position)).getId()); 
        videoDisplayIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        videoDisplayIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
        videoDisplayIntent.putExtra("VIDEO_ID", ((YTBVideo)videos.get(position)).getId()); 
        startActivity(videoDisplayIntent); 
       } 
       }); 
     progressDialog = ProgressDialog.show(this, "Loading Video Images", "Loading Video Images", true, false); 
     // setListAdapter(new MyThumbnaildapter(AndroidThumbnailList.this, R.layout.row, videoFileList)); 
    } 


    /*@Override 
    public void onCreateContextMenu(ContextMenu menu, View v, 
      ContextMenuInfo menuInfo) { 
     // TODO Auto-generated method stub 
     super.onCreateContextMenu(menu, v, menuInfo); 

    }*/ 

    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     try{ 
      DownloaderTAsk downloaderTAsk = (DownloaderTAsk) new DownloaderTAsk().execute(getApplicationContext()); 


     }catch (Exception e) { 
      // TODO: handle exception 
     } 
    } 


    class DownloaderTAsk extends AsyncTask{ 

     @Override 
     protected Object doInBackground(Object... arg0) { 
      // TODO Auto-generated method stub 
      try{ 
       printVideoFEEJSONString("http://gdata.youtube.com/feeds/api/videos?alt=jsonc&q=football+-soccer&orderby=published&start-index=11&max-results=10&v=2"); 
       //printVideoFEEJSONString("https://gdata.youtube.com/feeds/api/videos?alt=json&q=football+-soccer&orderby=published&start-index=11&max-results=10&v=2"); 
       imageLoaderHandler.sendEmptyMessage(0); 
      }catch (Exception e) { 
       // TODO: handle exception 
       e.printStackTrace(); 

       imageLoaderHandler.sendEmptyMessage(1); 

      } 
      return null; 
     } 
     @Override 
     protected void onPostExecute(Object result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 

     } 

    } 



    public void printVideoFEEJSONString(String feedURL){ 
     BufferedReader bufferedReader = null; 
     try{ 
      HttpClient client = new DefaultHttpClient(); 

      HttpGet request = new HttpGet(feedURL); 
      HttpResponse response = client.execute(request); 

      bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer jsonStringBuffer = new StringBuffer(""); 
      String line = ""; 
      String newLine = System.getProperty("line.separator"); 
      while ((line = bufferedReader.readLine()) != null) { 
       jsonStringBuffer.append(line + newLine); 
      } 

      String appUpdatorJsonString = jsonStringBuffer.toString(); 
      System.out.println("YOUTUBE VIDEO FEED JSON :"+appUpdatorJsonString); 

      JSONObject updaterAppJsonObject = new JSONObject(appUpdatorJsonString); 
      System.out.println("YOUTUBE VIDEO FEED JSON OBJECT :"+updaterAppJsonObject); 




      processYoutubeVideoFEEJSONObject(updaterAppJsonObject); 



     }catch (Exception e) { 
      e.printStackTrace(); 
      // TODO: handle exception 
     } 
    } 


    public void processYoutubeVideoFEEJSONObject(JSONObject updaterAppJsonObject){ 
     JSONObject dataJSONObject = null; 
     JSONArray itemsJSONArray = null; 
     JSONObject itemsJSONObject = null; 
     JSONObject linkJSONObject = null; 
     String yvURL = ""; 
     YTBVideo yVideo = null; 

     try{ 

      dataJSONObject = updaterAppJsonObject.getJSONObject("data"); 
      itemsJSONArray = dataJSONObject.getJSONArray("items"); 
      for(int i = 0; i < itemsJSONArray.length(); i++){ 
       yVideo = new YTBVideo(); 
       // for(int i = 0; i < 1; i++){ 
       itemsJSONObject = itemsJSONArray.getJSONObject(i); 
       yVideo.setId(itemsJSONObject.getString("id")); 
       yVideo.setThumbNailURL(itemsJSONObject.getJSONObject("thumbnail").getString("sqDefault")); 
       yVideo.setVideoImageURL(itemsJSONObject.getJSONObject("player").getString("default")); 
       yVideo.setTitle(itemsJSONObject.getString("title")); 
       yvURL = itemsJSONObject.getJSONObject("player").getString("default"); 


       String videoURL = yvURL.substring(0,yvURL.indexOf("&")); 
       vdoURL = videoURL; 
       System.out.println("Youtube URL is ::"+videoURL); 
       System.out.println("videoURL ::"+videoURL); 
       yVideo.setThumbnailImage(preloadBitmap(yVideo)); 
       videos.add(yVideo); 

      } 

     }catch (Exception e) { 
      e.printStackTrace(); 
      // TODO: handle exception 
     } 
    } 



    private Bitmap preloadBitmap(YTBVideo yTBVideo) throws MalformedURLException,IOException { 
     Bitmap photoBitmap= null; 
     try{ 

     BitmapFactory.Options imageOptions = null; 
     imageOptions = new BitmapFactory.Options(); 
     imageOptions.outHeight = 250; 
     imageOptions.outHeight = 150; 
     String FlickrPhotoPath = yTBVideo.getThumbNailURL(); 


     URL FlickrPhotoUrl = null; 


     System.out.println("FlickrPhotoPath:::::::"+FlickrPhotoPath); 
     //try { 
     FlickrPhotoUrl = new URL(FlickrPhotoPath); 

     HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection(); 
     httpConnection.setDoInput(true); 
     httpConnection.connect(); 
     InputStream inputStream = httpConnection.getInputStream(); 
     //photoBitmap = BitmapFactory.decodeStream(inputStream); 
     photoBitmap = BitmapFactory.decodeStream(inputStream,null,imageOptions); 
     System.out.println("photoBitmap:::::::"+photoBitmap); 
     /*} catch (MalformedURLException e) { 
       //e.printStackTrace(); 
      } catch (IOException e) { 
       //e.printStackTrace(); 
      }*/ 
     }catch (Exception e) { 
      // TODO: handle exception 
      //showErrorMessage("communication error", "Unable to connect to Flickr Server"); 
      e.printStackTrace(); 
     } 
     return photoBitmap; 
    } 

    protected void showErrorMessage(String messageLine1, String message) 
    {  
     noDataAlert = Utiliy.getAlertMessage(getBaseContext(), this, messageLine1.toUpperCase()+":\n"+message, 1); 
     noDataAlert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); 
     noDataAlert.setCanceledOnTouchOutside(true); 
     noDataAlert.setCancelable(true); 
     Button yesButton = (Button)noDataAlert.findViewById(R.id.alert_popup_yes_button); 
     yesButton.setText(" OK "); 
     yesButton.setTextSize(24); 
     yesButton.setPadding(5, 5, 5, 5); 
     yesButton.setVisibility(View.VISIBLE); 
     yesButton.setOnClickListener(new OnClickListener(){ 
      public void onClick(View view){ 
       noDataAlert.dismiss(); 
       finish(); 
      } 
     }); 
     noDataAlert.show(); 
    } 
} 

package com.test.utubevdo; 

    import java.util.List; 

    import com.keyes.youtube.OpenYouTubePlayerActivity; 

    import android.app.Activity; 
    import android.content.Intent; 
    import android.content.pm.PackageManager; 
    import android.content.pm.ResolveInfo; 
    import android.net.Uri; 
    import android.os.Bundle; 

    public class DisplayYoutubeVideo extends Activity { 

    String vdoID = ""; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     vdoID = (String) getIntent().getExtras().get("VIDEO_ID"); 

     System.out.println("vdoID :::"+vdoID); 
    } 
    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     startVideo(vdoID); 
    } 


    private void startVideo (String videoID) { // default youtube app 
     Intent i = new Intent (Intent . ACTION_VIEW , Uri . parse ("vnd.youtube:" + videoID)); 
     List <ResolveInfo> list = getPackageManager(). queryIntentActivities (i , PackageManager . MATCH_DEFAULT_ONLY); 
     if (list . size() == 0) { 
      //write you own activity to display the video, if default youtube video display class is not available or else use the default class it self 
      } 

     System.out.println("Intent Actin :"+i.getAction()); 
     startActivity (i); 
    } 
} 

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.test.utubevdo" 
     android:versionCode="1" 
     android:versionName="1.0"> 

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


    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/> 


    <application android:icon="@drawable/icon" android:label="@string/app_name"> 

    <activity android:name="com.test.utubevdo.AndroidThumbnailList" 
        android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

    <activity android:name="com.test.utubevdo.DisplayYoutubeVideo" 
        android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="com.test.utubevdo.VIEW_VIDEO" /> 
       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
相關問題