**前言: Android网络编程初始学习阶段,在网络上down了很多的代码.结果在自己实际亲测时出现了很多的问题,要么连接不上网络,要么就是获取不到网络的数据.经过Debug后发现了NetworkOnMainThreadException的异常,后来得知:对UI线程/主线程里面是不允许进行网络操作的,如果有网络操作,就会出现上述问题.
原因:
Android 4.0之后 (Android API > 9 Honeycomb及以后的版本)采用了严格模式,不允许在主线程中执行刷新,网络操作等费时操作.
- Thread Policy里对网络的限制
StrictMode.AndroidBlockGuardPolicy是BlockGuard.Policy的实现,在其onNetwork()方法里会根据Policy对网络操作检测:
public void onNetwork() {
if ((mPolicyMask & DETECT_NETWORK) == 0) {
return;
}
if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
throw new NetworkOnMainThreadException();
}
//...
}
主线程里的联网操作时会执行这里的onNetwork(),如果mPolicyMask里设置了PENALTY_DEATH_ON_NETWORK,NetworkOnMainThreadException异常就会被抛出。
而对mPolicyMask的PENALTY_DEATH_ON_NETWORK的掩码的使能操作,有两个方法:
StrictMode.ThreadPolicy.Builder().penaltyDeathOnNetwork()
StrictMode.enableDeathOnNetwork()
两种实现方式之方式一
使能主线程里的网络操作限制 从上面分析知道,主线程里的网络操作限制使能可以通过两个途径:
第一个StrictMode.ThreadPolicy.Builder().penaltyDeathOnNetwork(),只在StrictModeTest中被使用,tests编译时才会用到;
第二个StrictMode.enableDeathOnNetwork(),
在 ActiovityThread.handleBindApplication()中被使用:if (data.appInfo.targetSdkVersion > 9) { StrictMode.enableDeathOnNetwork(); } 在每个声明在sdk api-9以上的系统中应用,运行时都会被使能,也就是检测是否主线程中是否有联网操作,如果有联网操作就抛出NetworkOnMainThreadException异常。
第二中方式 — 我的方式
**将网络操作放入单开的线程之中.程序功能:
用户单击按钮,APP获取百度的内容,并将获取到的网络数据转存下来显示在
按钮下方的TextView之中.
该APP 通过 线程 和 Android消息机制 来完成功能,是主流的实现方式**
Post和Get方式都亲自测试,一切正常.
MySourceCode:
Activity:
package com.elvis.onlineandroid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private Button button;
private TextView textView;
private HttpResponse httpResponse=null;
private HttpEntity httpEntity=null;
public String resultString = null;
public MyThread mythread = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public class MyThread extends Thread
{
@Override
public void run() {
// TODO Auto-generated method stub
HttpPost httpPost = new HttpPost("http://www.baidu.com");
//HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpClient httpclient = new DefaultHttpClient();
InputStream inputstream = null;
try{
httpResponse = httpclient.execute(httpPost);
httpEntity = httpResponse.getEntity();
inputstream = httpEntity.getContent();
//流文件的读取
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputstream)
);
String lineString = "";
while((lineString =reader.readLine())!= null)
{
resultString = resultString + lineString;
}
Message msg = myHandler.obtainMessage(1,1,1,resultString);
myHandler.sendMessage(msg);
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
try{
inputstream.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.button1:
mythread = new MyThread();
mythread.start();
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void initView()
{
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
textView = (TextView)findViewById(R.id.textView2);
}
Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
textView.setText(msg.obj.toString());
}
};
}
XML布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="向百度发送一次请求" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="TextView" />
</RelativeLayout>
注意点:
涉及到APP访问网络,需要设置安卓网络访问权限:
AndroidManifest.xml文件中添加:
<uses-permission android:name="android.permission.INTERNET" />
下面的Code用到了Android消息机制.线程完成网络操作后 ,向myHandler发送消息(message),myHandler的handleMessage()方法实现网络文本内容显示在UI控件上.
核心点:一般的UI控件的操作,都要放在消息处理函数中进行.
Message msg = myHandler.obtainMessage(1,1,1,resultString);
myHandler.sendMessage(msg);
反思:网络上很多Code都只能提示大概,具体实践还要靠自己反复摸索.