Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中通過網絡獲取json數據來播放視頻

Android中通過網絡獲取json數據來播放視頻

編輯:關於Android編程

為了實現 本地化的測試 ,要新建 一個java 類做為 服務端 讓手機來訪問

把json放到你服務端tomcat 中 如圖 :

 

\

json數據 的內容 為:


[java]
{   
"videos":[   
    {   
        "id":"1",   
        "title":"泡芙小姐的燈泡",   
        "image":"http://172.22.64.28:8080/doudou/images/fu.jpg",   
        "duration":"910",   
        "category":"原創",   
        "state":"normal",   
        "published":"2011-07-15  09:00:42",   
        "description":"當一個人在一座城市搬11次家。就意味著准備在這個城市買房了",   
        "player":"http://172.22.64.28:8080/doudou/video/oppo.3gp"   
    },   
    {   
        "id":"2",   
        "title":"愛在春天",   
        "image":"http://172.22.64.28:8080/doudou/images/spring.jpg",   
        "duration":"910",   
        "category":"原創",   
        "state":"normal",   
        "published":"2013-04-15  09:00:42",   
        "description":"上世紀30年代中期,整個中國動蕩不安,幾個年輕女孩依然懷抱著勇氣,追尋著理想與愛情。",   
        "player":"http://172.22.64.28:8080/doudou/video/hao.3gp"   
    }   
  } 


"videos":[ 
    { 
        "id":"1", 
        "title":"泡芙小姐的燈泡", 
        "image":"http://172.22.64.28:8080/doudou/images/fu.jpg", 
        "duration":"910", 
        "category":"原創", 
        "state":"normal", 
        "published":"2011-07-15  09:00:42", 
        "description":"當一個人在一座城市搬11次家。就意味著准備在這個城市買房了", 
        "player":"http://172.22.64.28:8080/doudou/video/oppo.3gp" 
    }, 
    { 
        "id":"2", 
        "title":"愛在春天", 
        "image":"http://172.22.64.28:8080/doudou/images/spring.jpg", 
        "duration":"910", 
        "category":"原創", 
        "state":"normal", 
        "published":"2013-04-15  09:00:42", 
        "description":"上世紀30年代中期,整個中國動蕩不安,幾個年輕女孩依然懷抱著勇氣,追尋著理想與愛情。", 
        "player":"http://172.22.64.28:8080/doudou/video/hao.3gp" 
    } 
  }
}

 

[java]
public class ListVideoActivity extends Activity { 
 
    // 獲取視頻數據的地址  
    private String path = "http://172.22.64.28:8080/doudou/video.json"; 
 
    // 接受服務器端響應的數據  
    private String content; 
 
    // 聲明listView控件  
    private ListView listView; 
    // 聲明handler對象  
    private Handler handler; 
    private static final int INTENTDATA = 1; 
 
    public JSONArray array; 
 
    public LayoutInflater inflater; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_list_video); 
 
        // 根據服務獲取inflater對象  
        inflater = (LayoutInflater) this 
                .getSystemService(LAYOUT_INFLATER_SERVICE); 
        // 發送請求 獲取網絡數據  
        sendGet(); 
        // 獲取控件對象  
        listView = (ListView) findViewById(R.id.lv_videos); 
         
         
 
        // 實例化 handler操作  
        handler = new Handler() { 
 
            @Override 
            public void handleMessage(Message msg) { 
                super.handleMessage(msg); 
                switch (msg.what) { 
                case INTENTDATA: 
                    // 獲取數據操作  
                    // 判斷不為空 並且不等於""  
                    if (content != null && (!"".equals(content))) { 
                        try { 
                            // 把它轉換成json對象 {} []  
                            JSONObject obj = new JSONObject(content); 
                            array = obj.getJSONArray("videos"); 
                            listView.setAdapter(new VideoAdapter());// 設置顯示的視圖  
                             
                             
                            //listView注冊事件  
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
 
                                /**
                                 * parent :listView
                                 * view 每個條目控件
                                 * position:條目所在的位置
                                 * id:行號 0 
                                 */ 
                                @Override 
                                public void onItemClick(AdapterView<?> parent, View view, 
                                        int position, long id) { 
                                     
                                 
                                    JSONObject jsonObj = (JSONObject) parent.getItemAtPosition(position); 
                                     
                                    Intent intent = new Intent(ListVideoActivity.this,VideoViewActivity.class); 
                                 
                                    try { 
                                        intent.putExtra("path", jsonObj.getString("player")); 
                                        startActivity(intent); 
                                    } catch (JSONException e) { 
                                        // TODO Auto-generated catch block  
                                        e.printStackTrace(); 
                                    } 
                                     
                                } 
                                 
                            }); 
                             
                             
                        } catch (JSONException e) { 
                            System.out 
                                    .println("------------exeception-------------" 
                                            + e.getMessage()); 
                        } 
 
                    } 
 
                    break; 
 
                default: 
                    break; 
                } 
            } 
        }; 
 
    } 
 
    public void sendGet() { 
        // 操作發送網絡請求  
        new Thread(new Runnable() { 
            @Override 
            public void run() { 
                content = HttpUtils.sendGetClient(path); 
                // 發送消息  
                handler.sendEmptyMessage(ListVideoActivity.INTENTDATA); 
 
            } 
 
        }).start(); 
    } 
 
    class VideoAdapter extends BaseAdapter { 
 
        @Override 
        public int getCount() { 
 
            return array.length(); 
        } 
 
        @Override 
        public Object getItem(int position) { 
            // TODO Auto-generated method stub  
            try { 
                return array.get(position); 
            } catch (JSONException e) { 
                // TODO Auto-generated catch block  
                e.printStackTrace(); 
            } 
            return null; 
        } 
 
        @Override 
        public long getItemId(int position) { 
 
            return position; 
        } 
 
        @Override 
        public View getView(int position, View convertView, ViewGroup parent) { 
 
            // 創建一個顯示的控件 每個條目對應的控件  
            // 根據inflate方法 把一個布局文件轉換成View控件對象  
            View v = inflater.inflate(R.layout.activity_list, null); 
            // findViewById()來獲取View布局對象中的控件  
            TextView tv_title = (TextView) v.findViewById(R.id.tv_title); 
            TextView tv_duration = (TextView) v.findViewById(R.id.tv_duration); 
            TextView tv_date = (TextView) v.findViewById(R.id.tv_date); 
 
            ImageView iv_icon = (ImageView) v.findViewById(R.id.iv_image); 
            try { 
                JSONObject jsonObj = (JSONObject) array.get(position); 
                // 設置顯示控件的文本  
                tv_title.setText("標題:" + jsonObj.getString("title")); 
                tv_duration.setText("時長:" + jsonObj.getString("duration")); 
                tv_date.setText("發布時間:" + jsonObj.getString("published")); 
                 
                iv_icon.setId(R.drawable.ic_launcher);// 默認的圖標  
            } catch (Exception e) { 
                System.out.println("eeeee" + e.getMessage()); 
                e.printStackTrace(); 
            } 
            // 返回v對象  
            return v; 
        } 
 
    } 
 

public class ListVideoActivity extends Activity {

 // 獲取視頻數據的地址
 private String path = "http://172.22.64.28:8080/doudou/video.json";

 // 接受服務器端響應的數據
 private String content;

 // 聲明listView控件
 private ListView listView;
 // 聲明handler對象
 private Handler handler;
 private static final int INTENTDATA = 1;

 public JSONArray array;

 public LayoutInflater inflater;

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

  // 根據服務獲取inflater對象
  inflater = (LayoutInflater) this
    .getSystemService(LAYOUT_INFLATER_SERVICE);
  // 發送請求 獲取網絡數據
  sendGet();
  // 獲取控件對象
  listView = (ListView) findViewById(R.id.lv_videos);
  
  

  // 實例化 handler操作
  handler = new Handler() {

   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    switch (msg.what) {
    case INTENTDATA:
     // 獲取數據操作
     // 判斷不為空 並且不等於""
     if (content != null && (!"".equals(content))) {
      try {
       // 把它轉換成json對象 {} []
       JSONObject obj = new JSONObject(content);
       array = obj.getJSONArray("videos");
       listView.setAdapter(new VideoAdapter());// 設置顯示的視圖
       
       
       //listView注冊事件
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        /**
         * parent :listView
         * view 每個條目控件
         * position:條目所在的位置
         * id:行號 0
         */
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {
         
        
         JSONObject jsonObj = (JSONObject) parent.getItemAtPosition(position);
         
         Intent intent = new Intent(ListVideoActivity.this,VideoViewActivity.class);
        
         try {
          intent.putExtra("path", jsonObj.getString("player"));
          startActivity(intent);
         } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
         }
         
        }
        
       });
       
       
      } catch (JSONException e) {
       System.out
         .println("------------exeception-------------"
           + e.getMessage());
      }

     }

     break;

    default:
     break;
    }
   }
  };

 }

 public void sendGet() {
  // 操作發送網絡請求
  new Thread(new Runnable() {
   @Override
   public void run() {
    content = HttpUtils.sendGetClient(path);
    // 發送消息
    handler.sendEmptyMessage(ListVideoActivity.INTENTDATA);

   }

  }).start();
 }

 class VideoAdapter extends BaseAdapter {

  @Override
  public int getCount() {

   return array.length();
  }

  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   try {
    return array.get(position);
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return null;
  }

  @Override
  public long getItemId(int position) {

   return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   // 創建一個顯示的控件 每個條目對應的控件
   // 根據inflate方法 把一個布局文件轉換成View控件對象
   View v = inflater.inflate(R.layout.activity_list, null);
   // findViewById()來獲取View布局對象中的控件
   TextView tv_title = (TextView) v.findViewById(R.id.tv_title);
   TextView tv_duration = (TextView) v.findViewById(R.id.tv_duration);
   TextView tv_date = (TextView) v.findViewById(R.id.tv_date);

   ImageView iv_icon = (ImageView) v.findViewById(R.id.iv_image);
   try {
    JSONObject jsonObj = (JSONObject) array.get(position);
    // 設置顯示控件的文本
    tv_title.setText("標題:" + jsonObj.getString("title"));
    tv_duration.setText("時長:" + jsonObj.getString("duration"));
    tv_date.setText("發布時間:" + jsonObj.getString("published"));
    
    iv_icon.setId(R.drawable.ic_launcher);// 默認的圖標
   } catch (Exception e) {
    System.out.println("eeeee" + e.getMessage());
    e.printStackTrace();
   }
   // 返回v對象
   return v;
  }

 }

}
 

[java]
public class VideoViewActivity extends Activity { 
 
    private VideoView videoView; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        // 控件  
        this.setContentView(R.layout.activity_videoview); 
 
        videoView = (VideoView) findViewById(R.id.vv_video); 
 
        String path = this.getIntent().getStringExtra("path"); 
 
        if (path != null) { 
     
            // 指定播放的視頻文件即可  
            videoView.setVideoURI(Uri.parse(path)); 
            System.out.println(path); 
            // 設置視頻播放的控制器  
            videoView.setMediaController(new MediaController(this)); 
            // 視頻開始播放  
            videoView.start(); 
 
        } else { 
            Toast.makeText(this, "path路徑為空", Toast.LENGTH_LONG).show(); 
        } 
 
         
    } 

public class VideoViewActivity extends Activity {

 private VideoView videoView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // 控件
  this.setContentView(R.layout.activity_videoview);

  videoView = (VideoView) findViewById(R.id.vv_video);

  String path = this.getIntent().getStringExtra("path");

  if (path != null) {
 
   // 指定播放的視頻文件即可
   videoView.setVideoURI(Uri.parse(path));
   System.out.println(path);
   // 設置視頻播放的控制器
   videoView.setMediaController(new MediaController(this));
   // 視頻開始播放
   videoView.start();

  } else {
   Toast.makeText(this, "path路徑為空", Toast.LENGTH_LONG).show();
  }

  
 }
}
 

[java]
public class HttpUtils { 
    /**
     * httpClient發送的GET請求
     * 
     * @param path
     * @return
     */ 
    public static String sendGetClient(String path) { 
        String content = null; 
        try { 
            // 創建一個httpClient的客戶端對象  
            HttpClient httpClient = new DefaultHttpClient(); 
 
            // 發送的Get請求  
            HttpGet httpGet = new HttpGet(path); 
 
            // 客戶端  
            HttpResponse httpResponse = httpClient.execute(httpGet); 
 
            // 判斷服務端是否響應成功  
            if (httpResponse.getStatusLine().getStatusCode() == 200) { 
                // 獲取響應的內容  
                InputStream is = httpResponse.getEntity().getContent(); 
                byte data[] = StreamTools.isToData(is); 
                content = new String(data); 
                // 關閉流  
                is.close(); 
            } 
        } catch (IOException e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } 
 
        return content; 
 
    } 
 
    /**
     * httpclient客戶端發送Post請求
     * @param path
     * @param name
     * @param pass
     * @return
     */ 
    public static String sendPostClient(String path, String name, String pass) { 
        String content = null; 
 
        //創建一個httpClient對象  
        HttpClient httpClient = new DefaultHttpClient(); 
 
        //創建請求方式對象  path  
        HttpPost httpPost = new HttpPost(path); 
 
        //封裝請求的參數集合  
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); 
        parameters.add(new BasicNameValuePair("user.name", name)); 
        parameters.add(new BasicNameValuePair("user.pass", pass)); 
         
        UrlEncodedFormEntity entity = null; 
        try { 
            //封裝請參數的實體對象  
            entity = new UrlEncodedFormEntity(parameters, "UTF-8"); 
            //把參數設置到 httpPost中  
            httpPost.setEntity(entity); 
            //執行請求  
            HttpResponse httpResponse = httpClient.execute(httpPost); 
            //判斷響應是否成功  
            if (httpResponse.getStatusLine().getStatusCode() == 200) { 
                //獲取響應的內容  
                InputStream is = httpResponse.getEntity().getContent(); 
                //data  
                byte data[] = StreamTools.isToData(is); 
                //轉換成字符串  
                content = new String(data); 
            } 
 
        } catch (UnsupportedEncodingException e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } catch (ClientProtocolException e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } 
 
        return content; 
 
    } 

public class HttpUtils {
 /**
  * httpClient發送的GET請求
  *
  * @param path
  * @return
  */
 public static String sendGetClient(String path) {
  String content = null;
  try {
   // 創建一個httpClient的客戶端對象
   HttpClient httpClient = new DefaultHttpClient();

   // 發送的Get請求
   HttpGet httpGet = new HttpGet(path);

   // 客戶端
   HttpResponse httpResponse = httpClient.execute(httpGet);

   // 判斷服務端是否響應成功
   if (httpResponse.getStatusLine().getStatusCode() == 200) {
    // 獲取響應的內容
    InputStream is = httpResponse.getEntity().getContent();
    byte data[] = StreamTools.isToData(is);
    content = new String(data);
    // 關閉流
    is.close();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return content;

 }

 /**
  * httpclient客戶端發送Post請求
  * @param path
  * @param name
  * @param pass
  * @return
  */
 public static String sendPostClient(String path, String name, String pass) {
  String content = null;

  //創建一個httpClient對象
  HttpClient httpClient = new DefaultHttpClient();

  //創建請求方式對象  path
  HttpPost httpPost = new HttpPost(path);

  //封裝請求的參數集合
  List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
  parameters.add(new BasicNameValuePair("user.name", name));
  parameters.add(new BasicNameValuePair("user.pass", pass));
  
  UrlEncodedFormEntity entity = null;
  try {
   //封裝請參數的實體對象
   entity = new UrlEncodedFormEntity(parameters, "UTF-8");
   //把參數設置到 httpPost中
   httpPost.setEntity(entity);
   //執行請求
   HttpResponse httpResponse = httpClient.execute(httpPost);
   //判斷響應是否成功
   if (httpResponse.getStatusLine().getStatusCode() == 200) {
    //獲取響應的內容
    InputStream is = httpResponse.getEntity().getContent();
    //data
    byte data[] = StreamTools.isToData(is);
    //轉換成字符串
    content = new String(data);
   }

  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return content;

 }
}
 

[java]
public class NetWorkUtils { 
 
    private Context context; 
 
    // 網路鏈接管理對象  
    public ConnectivityManager connectivityManager; 
 
    public NetWorkUtils(Context context) { 
        this.context = context; 
        // 獲取網絡鏈接的對象  
        connectivityManager = (ConnectivityManager) context 
                .getSystemService(Context.CONNECTIVITY_SERVICE); 
    } 
 
    public boolean setActiveNetWork() { 
         
        boolean flag =false; 
        // 獲取可用的網絡鏈接對象  
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); 
        if (networkInfo == null) { 
            new AlertDialog.Builder(context) 
                    .setTitle("網絡不可用") 
                    .setMessage("可以設置網絡?") 
                    .setPositiveButton("確認", 
                            new DialogInterface.OnClickListener() { 
                                @Override 
                                public void onClick(DialogInterface dialog, 
                                        int which) { 
                                    Toast.makeText(context, "點擊確認", 
                                            Toast.LENGTH_LONG).show(); 
 
                                     
                                    // 聲明意圖  
                                    Intent intent = new Intent(); 
                                    intent.setAction(Intent.ACTION_MAIN); 
                                    intent.addCategory("android.intent.category.LAUNCHER"); 
                                    intent.setComponent(new ComponentName( 
                                            "com.android.settings", 
                                            "com.android.settings.Settings")); 
                                    intent.setFlags(0x10200000); 
                                    // 執行意圖  
                                    context.startActivity(intent); 
 
                                } 
 
                            }) 
                    .setNegativeButton("取消", 
                            new DialogInterface.OnClickListener() { 
 
                                @Override 
                                public void onClick(DialogInterface dialog, 
                                        int which) { 
                                } 
 
                            }).show();// 必須.show();  
             
 
        } 
        //判斷網絡是否可用  
        if(networkInfo!=null){ 
            flag =true; 
        } 
        return flag; 
    } 

public class NetWorkUtils {

 private Context context;

 // 網路鏈接管理對象
 public ConnectivityManager connectivityManager;

 public NetWorkUtils(Context context) {
  this.context = context;
  // 獲取網絡鏈接的對象
  connectivityManager = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
 }

 public boolean setActiveNetWork() {
  
  boolean flag =false;
  // 獲取可用的網絡鏈接對象
  NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  if (networkInfo == null) {
   new AlertDialog.Builder(context)
     .setTitle("網絡不可用")
     .setMessage("可以設置網絡?")
     .setPositiveButton("確認",
       new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog,
          int which) {
         Toast.makeText(context, "點擊確認",
           Toast.LENGTH_LONG).show();

         
         // 聲明意圖
         Intent intent = new Intent();
         intent.setAction(Intent.ACTION_MAIN);
         intent.addCategory("android.intent.category.LAUNCHER");
         intent.setComponent(new ComponentName(
           "com.android.settings",
           "com.android.settings.Settings"));
         intent.setFlags(0x10200000);
         // 執行意圖
         context.startActivity(intent);

        }

       })
     .setNegativeButton("取消",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int which) {
        }

       }).show();// 必須.show();
   

  }
  //判斷網絡是否可用
  if(networkInfo!=null){
   flag =true;
  }
  return flag;
 }
}
 

[java]
public class StreamTools { 
 
     
    public static byte[] isToData(InputStream is) throws IOException{ 
        // 字節輸出流  
        ByteArrayOutputStream bops = new ByteArrayOutputStream(); 
        // 讀取數據的緩存區  
        byte buffer[] = new byte[1024]; 
        // 讀取長度的記錄  
        int len = 0; 
        // 循環讀取  
        while ((len = is.read(buffer)) != -1) { 
            bops.write(buffer, 0, len); 
        } 
        // 把讀取的內容轉換成byte數組  
        byte data[] = bops.toByteArray(); 
         
        bops.flush(); 
        bops.close(); 
        is.close(); 
        return data; 
    } 

public class StreamTools {

 
 public static byte[] isToData(InputStream is) throws IOException{
  // 字節輸出流
  ByteArrayOutputStream bops = new ByteArrayOutputStream();
  // 讀取數據的緩存區
  byte buffer[] = new byte[1024];
  // 讀取長度的記錄
  int len = 0;
  // 循環讀取
  while ((len = is.read(buffer)) != -1) {
   bops.write(buffer, 0, len);
  }
  // 把讀取的內容轉換成byte數組
  byte data[] = bops.toByteArray();
  
  bops.flush();
  bops.close();
  is.close();
  return data;
 }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved