解决4.0后android.os.NetworkOnMainThreadException错误
来源:互联网 发布:nc57数据字典下载 编辑:程序博客网 时间:2024/05/03 00:22
Android SDK 2.0中访问网络不会出现android.os.NetworkOnMainThreadException异常错误,但在 4.0之后运行则会报此错误(即在主线程访问网络时发生异常)。
原因就是Android在4.0之前的版本都支持在主线程中访问网络,但在4.0以后对这部分程序进行了优化,若在主线程里执行Http请求都会报错,
其原则就是:UI线程不能有任何的网络访问操作。
解决办法有两个思路,分别是:?1234if
(android.os.Build.VERSION.SDK_INT >
9
) {
StrictMode.ThreadPolicy policy =
new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
从 Android 2.3 开始提供了一个新的类 StrictMode,该类可以用于捕捉发生在应用程序主线程中耗时的磁盘、网络访问或函数调用,可以帮助开发者改进程序,
if
(android.os.Build.VERSION.SDK_INT >
9
) {
StrictMode.ThreadPolicy policy =
new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
使主线程处理 UI 和动画在磁盘读写和网络操作时变得更平滑,避免主线程被阻塞。?1234567891011121314151617181920212223242526272829public
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);
}
}
举例:如下获取Json字符串的方法在UI主线程中,就会报错:android.os.NetworkOnMainThreadException?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071public
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;
}
}
正确的做法:可以采用AsyncTack?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475public
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
}
}
在主线程中只需执行如下调用:?12mJSONParser =
new
JSONParser();
mJSONParser.execute();
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);
}
}
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;
}
}
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
}
}
mJSONParser =
new
JSONParser();
mJSONParser.execute();
第一种:强制使用以下更改,即在MainActivity的setContentView(R.layout.activity_main)下添加如下代码:
第二种:使用Thread、Runnable、Handler。即在Runnable中做HTTP请求,不用阻塞UI线程。
第二种方法就是多线程访问,因此可以采用AsyncTask任务方式也是相通的。
- 解决4.0后android.os.NetworkOnMainThreadException错误
- android.os.NetworkOnMainThreadException错误
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- 解决android.os.NetworkOnMainThreadException
- C++必知必会之(29)虚构造函数与Prototype模式
- 迷茫了
- 程序人生的四个象限和两条主线
- 论研发团队的演化--微观篇--续
- USB 基本知识(五)-----高速USB设计PCB布线要求(partial)
- 解决4.0后android.os.NetworkOnMainThreadException错误
- svn常用命令
- 很少人知道但很有用的 Linux 命令
- Eclipse javah 配置
- 关于UIViewController self.title在IOS7中默认是黑色且字体稍小的解决办法
- 离散傅立叶之听声音破解拨号健
- asp.net DataSet转换成josn并输出
- lsof 的参数详解
- Mysql监控指南(实践的好文章值得收藏)