W / System.err(21922):android.os.NetworkOnMainThreadException

时间:2015-07-07 18:02:50

标签: android broadcastreceiver

我有一个checkboxlist,用户选择了一些我喜欢用json格式选择的项目,然后我将json字符串从alarmManager发送到GetLLRD类。目前我在IntentService类中接收意图有问题,因为我在OnHandleIntent中的意图不是每60秒,而是在下面的输出中显示的不同时间。

我在IntentReceiver那里尝试过,我按计划得到了输出。因此,我想从HttpUrlConenction中的onReceive方法启动IntentReceiver。我已经尝试了但是我收到警告,如android.os.NetworkOnMainThreadException,我没有任何互联网连接问题,因为我有另一个AsynTask类,它们在应用程序中向/从服务器发送和接收请求。

我可以从BroadcastReceiver发送HttpUtlConenction请求以及我做错了吗?

部分输出:

07-07 19:39:06.805: I/System.out(7534): test from the onHandleIntent{"selected":[6,9]}
07-07 19:39:19.417: I/System.out(7534): test from the onHandleIntent{"selected":[6]}
07-07 19:39:19.417: I/System.out(7534): test from the onHandleIntent{"selected":[6,9]}
07-07 19:39:30.378: I/System.out(7534): test from the onHandleIntent{"selected":[6,9]}
07-07 19:39:45.323: I/System.out(7534): test from the onHandleIntent{"selected":[6,9]}

MainActivity类:

                    Intent intent = new Intent(MainActivity.this,
                            IntentReceiver.class);
                    intent.putExtra("json_data", json);
                    PendingIntent pendingIntent = PendingIntent.getService(
                            getApplicationContext(), 3, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    Calendar cal = Calendar.getInstance();
                    alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                            System.currentTimeMillis(), 60 * 1000,
                            pendingIntent);
                    // cal.getTimeInMillis()
                    startService(intent);

GetLLRD课程:

public class GetLLRD extends IntentService {

    public GetLLRD() {
        super("IntentService");

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String jSONString = intent.getStringExtra("json_data");
        System.out.println("test from the onHandleIntent" + jSONString);
        if(jSONString != null){

            System.out.println("Test");
        }

    }
}

IntentReceiver:

public class IntentReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getStringExtra("json_data");

            if (!action.isEmpty()) {
                System.out.println("test from IntentReiceier" + action);

             BufferedReader reader = null;

            try {

                URL myUrl = new URL(
                        "https://apple-bustracker.rhcloud.com/webapi/test");

                HttpURLConnection conn = (HttpURLConnection) myUrl
                        .openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();
                // create data output stream
                DataOutputStream wr = new DataOutputStream(
                        conn.getOutputStream());
                // write to the output stream from the string
                wr.writeBytes(jsonString);

                wr.close();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }

                try {
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<ItemDTO>>() {
                    }.getType();
                    data = gson.fromJson(sb.toString(), listType);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                for (ItemDTO itemDTO : data) {
                    double latitude = itemDTO.getLatitude();
                    double longitude = itemDTO.getLongitude();
                    int route = itemDTO.getRoute();
                    String direction = itemDTO.getDirection();
                    System.out.println("test" + latitude + ", " + longitude + ", "
                            + ", " + route + ", " + direction);

                }


            } catch (IOException e) {

                e.printStackTrace();

            } finally {
                if (reader != null) {
                    try {
                        reader.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }


            }
        } catch (Exception e) {
        }

    }


}

2 个答案:

答案 0 :(得分:2)

  

我可以从BroadcastReceiver

发送HttpUtlConenction请求吗?

没有。在主应用程序线程上调用onReceive(),您不应在主应用程序线程上执行磁盘I / O或网络I / O.将该HTTP代码移到另一个IntentService,然后从startService()调用IntentService上的onReceive()

答案 1 :(得分:0)

IntentReceiver中的行为正在主线程中执行。网络访问必须从后台线程完成,因此应该通过IntentService将其移动到后台线程。例如:

 public class IntentReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {
        Intent intentForService = new Intent(context, MyIntentService.class);

        intentForService.setAction(intent.getAction());
        intentForService.setData(intent.getData());
        intentForService.replaceExtras(intent.getExtras());

        context.startService(intentForService);
    }
 }

然后

 public class MyIntentService extends IntentService {
     //You'll need some boilerplate like the constructor for this new class

     @Override
     protected void onHandleIntent(final Intent intent) {
          //Your current behavior in IntentReceiver goes here
     }
 }