Android中通过网络获取json数据来播放视频

为了实现 本地化的测试 ,要新建 一个java 类做为 服务端 让手机来访问

把json放到你服务端tomcat 中 如图 :

Android中通过网络获取json数据来播放视频_第1张图片

json数据 的内容 为:

{  
"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"  
    }  
  }
}

 

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 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 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 parameters = new ArrayList();
		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 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 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;
	}
}


 


   

 

完整代码请访问:http://download.csdn.net/detail/chrp99/5629565



你可能感兴趣的:(Android,Android开发详解)