Android SDK 2.0中访问网络不会出现android.os.NetworkOnMainThreadException异常错误,但在 4.0之后运行则会报此错误(即在主线程访问网络时发生异常)。
原因就是Android在4.0之前的版本都支持在主线程中访问网络,但在4.0以后对这部分程序进行了优化,若在主线程里执行Http请求都会报错,
其原则就是:UI线程不能有任何的网络访问操作。
解决办法有两个思路,分别是:?
1
2
3
4
|
if
(android.os.Build.VERSION.SDK_INT >
9
) {
StrictMode.ThreadPolicy policy =
new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
|
使主线程处理 UI 和动画在磁盘读写和网络操作时变得更平滑,避免主线程被阻塞。?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
this
.setContentView(R.layout.share_mblog_view);
new
Thread(runnable).start();
}
Handler handler =
new
Handler(){
@Override
public
void
handleMessage(Message msg) {
super
.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString(
"value"
);
Log.i(
"mylog"
,
"请求结果-->"
+ val);
}
}
Runnable runnable =
new
Runnable(){
@Override
public
void
run() {
//
// TODO: http request.
//
Message msg =
new
Message();
Bundle data =
new
Bundle();
data.putString(
"value"
,
"请求结果"
);
msg.setData(data);
handler.sendMessage(msg);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
public
class
JSONParser {
static
InputStream is =
null
;
static
JSONObject jObj =
null
;
static
String json =
""
;
// constructor
public
JSONParser() {
}
public
JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient =
new
DefaultHttpClient();
HttpGet httpPost =
new
HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpPost);
final
int
statusCode = getResponse.getStatusLine().getStatusCode();
if
(statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error "
+ statusCode +
" for URL "
+ url);
return
null
;
}
HttpEntity getResponseEntity = getResponse.getEntity();
//HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
is = getResponseEntity.getContent();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(ClientProtocolException e) {
e.printStackTrace();
}
catch
(IOException e) {
Log.d(
"IO"
, e.getMessage().toString());
e.printStackTrace();
}
try
{
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(
is,
"iso-8859-1"
),
8
);
StringBuilder sb =
new
StringBuilder();
String line =
null
;
while
((line = reader.readLine()) !=
null
) {
sb.append(line +
"\n"
);
}
is.close();
json = sb.toString();
}
catch
(Exception e) {
Log.e(
"Buffer Error"
,
"Error converting result "
+ e.toString());
}
// try parse the string to a JSON object
try
{
jObj =
new
JSONObject(json);
}
catch
(JSONException e) {
Log.e(
"JSON Parser"
,
"Error parsing data "
+ e.toString());
}
// return JSON String
return
jObj;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
public
class
JSONParser
extends
AsyncTask <String, Void, String>{
static
InputStream is =
null
;
static
JSONObject jObj =
null
;
static
String json =
""
;
// constructor
public
JSONParser() {
}
@Override
protected
String doInBackground(String... params) {
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient =
new
DefaultHttpClient();
HttpGet httpPost =
new
HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpPost);
final
int
statusCode = getResponse.getStatusLine().getStatusCode();
if
(statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error "
+ statusCode +
" for URL "
+ url);
return
null
;
}
HttpEntity getResponseEntity = getResponse.getEntity();
//HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
is = getResponseEntity.getContent();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(ClientProtocolException e) {
e.printStackTrace();
}
catch
(IOException e) {
Log.d(
"IO"
, e.getMessage().toString());
e.printStackTrace();
}
try
{
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(
is,
"iso-8859-1"
),
8
);
StringBuilder sb =
new
StringBuilder();
String line =
null
;
while
((line = reader.readLine()) !=
null
) {
sb.append(line +
"\n"
);
}
is.close();
json = sb.toString();
}
catch
(Exception e) {
Log.e(
"Buffer Error"
,
"Error converting result "
+ e.toString());
}
// try parse the string to a JSON object
try
{
jObj =
new
JSONObject(json);
}
catch
(JSONException e) {
Log.e(
"JSON Parser"
,
"Error parsing data "
+ e.toString());
}
// return JSON String
return
jObj;
}
protected
void
onPostExecute(String page)
{
//onPostExecute
}
}
|
1
2
|
mJSONParser =
new
JSONParser();
mJSONParser.execute();
|