public class MainActivity extends Activity {
private EditText address;
private Button getbutton;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
//版本4.0後需加這個,不然就報錯android.os.NetworkOnMainThreadException
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
//
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
//初始化
address = (EditText) findViewById(R.id.address);
getbutton = (Button) findViewById(R.id.getbutton);
text = (TextView) findViewById(R.id.text);
getbutton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = address.getText().toString();
getPDAServerData(url);
}
});
}
public void getPDAServerData(String url) {
HttpClient client = new DefaultHttpClient();
HttpPost request;
try {
request = new HttpPost(url);
//調用HttpClient對象的execute(HttpUriRequest request)發送請求,返回一個HttpResponse
HttpResponse response = client.execute(request);
//返回響應碼為200
if (response.getStatusLine().getStatusCode() == 200) {
//從響應中獲取消息實體
HttpEntity entity = response.getEntity();
if (entity != null) {
String out = EntityUtils.toString(entity);
text.setText(out);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
請問,
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
這段代碼的意思是什麼呢,為什麼不加,就無法執行訪問網絡的代碼語句呢。
request = new HttpPost(url);
//調用HttpClient對象的execute(HttpUriRequest request)發送請求,返回一個HttpResponse
HttpResponse response = client.execute(request);
這部分是網絡操作,必須在子線程執行,沒有這段代碼就會拋出android.os.NetworkOnMainThreadException;
而這個StrictMode主要是用來調試程序的,這段代碼可以檢測到android.os.NetworkOnMainThreadException
異常並發出警告 penaltyLog()表示將警告輸出到LogCat。
StrictMode 用法:http://www.2cto.com/kf/201503/381354.html