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

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

我有一个复选框列表,用户可以在其中选择一些我正在以 json 格式包围他的选择的项目,然后我将 json 字符串从 alarmManager 发送到 GetLLRD class。目前我在 IntentService class 中接收意图时遇到问题,因为我不是每 60 秒在 OnHandleIntent 中获取意图,而是在不同的时间获取意图,如下面的输出所示。

我已经用 IntentReceiver 试过了,我按计划得到了输出。因此,我想从 IntentReceiver 中的 onReceive 方法开始我的 HttpUrlConenction。我已经尝试过了,但是我收到了类似 android.os.NetworkOnMainThreadException 的警告,其中我对互联网连接没有任何问题,因为我有另一个 AsynTask classes 发送和获取请求 to/from 服务器中的应用程序。

我可以从 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]}

MainActivityclass:

                    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 class:

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) {
        }

    }


}

Can I send HttpUtlConenction request from BroadcastReceiver

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

调用 IntentService 上的 startService()

你的行为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
     }
 }