Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 透過網路取得 JSON 資料播放影片的實作

編輯:關於 Android 程式設計

為了在本地端進行測試,我們先建立一個 Java 類別充當伺服器端,讓手機得以存取,並把 JSON 檔放進伺服器的 tomcat 中:

JSON 資料內容如下:

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

接著是列表畫面 ListVideoActivity,負責發送請求、解析 JSON、以 ListView 呈現,並處理點擊事件跳轉到播放頁:

public class ListVideoActivity extends Activity {
 private String path = "https://172.22.64.28:8080/doudou/video.json";
 private String content;
 private ListView listView;
 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 = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
  sendGet();
  listView = (ListView) findViewById(R.id.lv_videos);
  handler = new Handler() {
   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    switch (msg.what) {
    case INTENTDATA:
     if (content != null && (!"".equals(content))) {
      try {
       JSONObject obj = new JSONObject(content);
       array = obj.getJSONArray("videos");
       listView.setAdapter(new VideoAdapter());
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @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) {
          e.printStackTrace();
        }
       }
      });
     } catch (JSONException e) {
      e.printStackTrace();
     }
    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) {
   try {
    return array.get(position);
   } catch (JSONException e) {
    e.printStackTrace();
   }
   return null;
  }
  @Override
  public long getItemId(int position) {
   return position;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   View v = inflater.inflate(R.layout.activity_list, null);
   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) {
    e.printStackTrace();
   }
   return v;
  }
 }
}

播放頁 VideoViewActivity 接收傳入的影片路徑,以 VideoView 播放並掛上 MediaController:

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));
   videoView.setMediaController(new MediaController(this));
   videoView.start();
  } else {
   Toast.makeText(this, "path路徑為空", Toast.LENGTH_LONG).show();
  }
}
}

HttpUtils 封裝了以 HttpClient 發送 GET 與 POST 請求的方法:

public class HttpUtils {
 public static String sendGetClient(String path) {
  String content = null;
  try {
   HttpClient httpClient = new DefaultHttpClient();
   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) {
   e.printStackTrace();
  }
  return content;
}
 public static String sendPostClient(String path, String name, String pass) {
  String content = null;
  HttpClient httpClient = new DefaultHttpClient();
  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.setEntity(entity);
   HttpResponse httpResponse = httpClient.execute(httpPost);
   if (httpResponse.getStatusLine().getStatusCode() == 200) {
    InputStream is = httpResponse.getEntity().getContent();
    byte data[] = StreamTools.isToData(is);
    content = new String(data);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return content;
}
}

NetWorkUtils 負責檢查網路連線狀態,若不可用則跳出提示對話框引導使用者前往設定:

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) {
      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();
  }
  if(networkInfo != null){
   flag = true;
  }
  return flag;
 }
}

StreamTools 提供將 InputStream 轉為 byte 陣列的輔助方法:

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 data[] = bops.toByteArray();
  bops.flush();
  bops.close();
  is.close();
  return data;
 }
}

整體流程是:ListVideoActivity 在背景執行緒發送請求取得 JSON,透過 Handler 回到主線程解析資料並以 ListView 呈現;使用者點擊項目後,取出 player 欄位的影片網址,透過 Intent 傳給 VideoViewActivity 播放。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved