Android IntententService中的NetworkOnMainThreadException

Android IntententService中的NetworkOnMainThreadException,android,intentservice,networkonmainthread,Android,Intentservice,Networkonmainthread,我有一个IntentService执行网络操作(HTTP POST),但它显示了NetworkOnMainThreadException。如果我是对的,IntentService将在单独的线程上运行。有人能告诉我为什么抛出这个异常吗?我的代码是: public class UpdateService extends IntentService { public static final int UPDATE_PROGRESS = 8344; BroadcastReceiver broadcast

我有一个IntentService执行网络操作(HTTP POST),但它显示了NetworkOnMainThreadException。如果我是对的,IntentService将在单独的线程上运行。有人能告诉我为什么抛出这个异常吗?我的代码是:

public class UpdateService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
BroadcastReceiver broadcastReceiver;
public UpdateService() {
    super("UpdateService");
}
@Override
protected void onHandleIntent(Intent intent) {

        if (broadcastReceiver == null) {

            broadcastReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {

                    Bundle extras = intent.getExtras();

                    NetworkInfo info = (NetworkInfo) extras.getParcelable("networkInfo");

                    State state = info.getState();
                    if (state == State.CONNECTED) {

                        onNetworkUp();

                    } else {

                    }
                }
            };

            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(broadcastReceiver, intentFilter);
        }
}

@Override
public void onDestroy(){
    unregisterReceiver(broadcastReceiver);
    }

void onNetworkUp(){
    String aDataRow = "";
    try {
        File myFile = new File( Environment.getExternalStorageDirectory().getPath() + "/myFile.txt");
        FileReader fr = new FileReader(myFile);
        BufferedReader myReader = new BufferedReader(fr);   
        while ((aDataRow = myReader.readLine()) != null) 
        updateLyne(aDataRow); //
        fr.close();
    } catch (Exception e) {
        Log.e("onNetworkUp",e.toString());
    }   


    void updateLyne(String aDataRow){
    JSONParser jsonParser = new JSONParser();
    String[] words = aDataRow.split(" ");
    pid = words[1];
    String rtime = aDataRow;
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(TAG_PID, pid));
    params.add(new BasicNameValuePair(TAG_TIME, rtime));

    JSONObject json = null;
    if (words[0].equalsIgnoreCase("cancel")){
        json = jsonParser.makeHttpRequest(url_cancel, "POST", params);                  
    }
    else{
        Log.d("empty","file empty!!");
    }

    try {
        int success = json.getInt("success");

        if (success == 1) {
            delLine(aDataRow); // delete the line
        } else {
            Log.d("pid="+pid+" not on board", "failed in deleting");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
}
公共类更新服务扩展了IntentService{
公共静态最终int更新_进度=8344;
广播接收机广播接收机;
公共更新服务(){
超级(“更新服务”);
}
@凌驾
受保护的手部内容无效(意图){
if(broadcastReceiver==null){
broadcastReceiver=新的broadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
Bundle extras=intent.getExtras();
NetworkInfo=(NetworkInfo)额外的getParcelable(“NetworkInfo”);
State State=info.getState();
if(state==state.CONNECTED){
onNetworkUp();
}否则{
}
}
};
final IntentFilter IntentFilter=新IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(广播接收器、意向过滤器);
}
}
@凌驾
公共空间{
未注册接收器(广播接收器);
}
void onNetworkUp(){
字符串aDataRow=“”;
试一试{
File myFile=新文件(Environment.getExternalStorageDirectory().getPath()+“/myFile.txt”);
FileReader fr=新的FileReader(myFile);
BufferedReader myReader=新的BufferedReader(fr);
而((aDataRow=myReader.readLine())!=null)
updateLyne(aDataRow)//
fr.close();
}捕获(例外e){
Log.e(“onNetworkUp”,e.toString());
}   
void updateLyne(字符串aDataRow){
JSONParser JSONParser=新的JSONParser();
String[]words=aDataRow.split(“”);
pid=字[1];
字符串rtime=aDataRow;
List params=new ArrayList();
参数添加(新的BasicNameValuePair(TAG_PID,PID));
添加参数(新的BasicNameValuePair(标记时间,rtime));
JSONObject json=null;
if(字[0]。相等信号情况(“取消”)){
json=jsonParser.makeHttpRequest(url_cancel,“POST”,params);
}
否则{
Log.d(“空”、“文件空!!”);
}
试一试{
int success=json.getInt(“success”);
如果(成功==1){
delLine(aDataRow);//删除该行
}否则{
Log.d(“pid=“+pid+”不在船上”,“删除失败”);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
下面给出了JSONParser.java

    public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        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;

}
    }
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}

问题是您没有在
onHandleIntent()中运行网络请求
,您只是创建并注册了一个
BroadcastReceiver
的实例。实际的网络请求不会在那里运行。它将在
BroadcastReceiver
收到消息时运行,这发生在UI线程上。正确的方案是在其他地方创建您的
BroadcastReceiver
,并在收到消息时运行收到后,启动一个
IntentService
,该服务在
onHandleIntent()
内执行一个网络调用-然后它确实会在工作线程上运行。希望这能有所帮助。

问题是您没有在
onHandleIntent()中运行网络请求
,您只是创建并注册了一个
BroadcastReceiver
的实例。实际的网络请求不会在那里运行。它将在
BroadcastReceiver
收到消息时运行,这发生在UI线程上。正确的方案是在其他地方创建您的
BroadcastReceiver
,并在收到消息时运行收到后,启动一个
IntentService
,该服务在
onHandleIntent()内执行网络调用
-然后它确实会在工作线程上运行。希望这有帮助。

你是在Android 3.0或更高版本上尝试此代码吗?@Bigflow.Yes。我在ICS上写。我想你只会在3.0以上遇到这样的异常。是的,没错,看看sajmon_d的答案。你是在Android 3.0或更高版本上尝试此代码吗?@Bigflow.Yes。我在IC上写我想只有在3.0以上,你才会得到这样的例外