android App中的网络访问

本文介绍了Android App中进行网络访问的必要性,并详细阐述了如何在AndroidManifest.xml中添加权限,以及避免NetworkOnMainThreadException的方法,如使用AsyncTask。提供了一个简单的GET请求示例,并展示了在AsyncTask中调用网络请求的代码片段,适用于更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单机app在android的生态环境中几乎没有立足之地,因此app获取网络访问权的能力是必不可少的,本文除了代码之外还包括一些注意事项(可能是太基础了所以书上或者其他参考网站都没有提及这些细节)。

一,在AndroidManifest.xml中加入访问互联网的权限:
< uses-permission android:name = "android.permission.INTERNET" />

二,访问互联网的操作不能在main thread (对于activity来说是UI thread)中进行,否则会报错:
”android.os.NetworkOnMainThreadException“
可选的方式有:
1, 使用AsyncTask处理网络操作。
2, 在activity中创建新thread处理网络操作。
3, 启动service并在service中创建新thread处理网络操作。

三,下面以简单的GET方式作为例子说明。
1, 访问互联网的主函数:
	 public String executeHttpGet(){
		 BufferedReader in = null;
		 String result = "empty";
		 String weather = "http://m.weather.com.cn/data/101280601.html";
		 
		 try{
			 DefaultHttpClient client = new DefaultHttpClient();
			 HttpGet request = new HttpGet();
			 request.setURI(new URI(weather)); // url max length = 2048, need to do POST if u wanna long request
			 HttpResponse response = client.execute(request);
			 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			 
			 StringBuffer sb = new StringBuffer();
			 String line = "";
			 String NL = System.getProperty("line.separator");
			 
			 while((line=in.readLine()) != null){
				 sb.append(line + NL);
			 }
			 
			 result = sb.toString();
			 // Log.d(DEBUG_TAG, result);
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 if(in != null){
				 try{
					 in.close();
				 }catch(Exception e){
					 e.printStackTrace();
				 }
			 }
		 }
		 
		 return result;
	 }

2, 在AsyncTask的doInBackground里面调用这个函数:
	 class HttpTask extends AsyncTask<Integer, Integer, String>{

		 @Override
		 protected String doInBackground(Integer... params) {
		 	return executeHttpGet();
		 }
		 
		 @Override
		 protected void onPostExecute(String result){ // update UI when process done
			 Log.e(DEBUG_TAG, "onPostExecute");
			 if(mTextView != null)
			 	mTextView.setText(result);
			 super.onPostExecute(result); 
		 }
		 
	}

3, 在UI线程中启动task:
	 public void onCreate(Bundle savedInstanceState){
	     super.onCreate(savedInstanceState);
	     setContentView(R.layout.http1);
	        ... ... // other initialization
	     new HttpTask().execute();
	    } // end of onCreate

* AsyncTask的使用还需要优化,这里仅作为demo简单实现。上述代码在N880E上验证通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值