NetworkOnMainThreadException

白昼怎懂夜的黑 提交于 2019-11-25 21:40:40

问题


I just found out about NetworkOnMainThreadException at official docs

and was wondering if the emulator is throwing this. I have been testing my app quite a bit and as far as I know all networking is off the main thread (using Roboguice RoboAsyncTask) but you never know if one has not escaped.

I am also using StrictMode and have not seen anything.

  1. Is my code just clean or is this not thrown on the emulator?

  2. How are we supposed to prepare for this happening in production?

  3. What about a grace period or something? Or is that elapsed now ;-) ??


回答1:


With honeycomb you can not perform a networking operation on its main thread as documentation says. For this reason you must use handler or asynctask. There is no another way to do it.

here you can find 2 examples written in turkish about networking operation. maybe they help.

  • 3. party kütüphane kullanmadan (ksoap2), (it includes english translation)

  • AsyncTask class'tan dönen parametreyi handle etmek. , google translate




回答2:


I have tested this and it does in fact happen on the emulator as well. Better make sure you test your app at least on the emulator if you plan to get it onto the 3.0 tablets and beyond.




回答3:


NetworkOnMainThreadException occurs when some networking operations are performed inside main method; I mean Oncreate(). You can use AsyncTask for resolving this issue. or you can use

StrictMode.ThreadPolicy mypolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

inside onCreate() method.




回答4:


If you are running on 3.0, i can't help; Because Strict mode is on by default in it; But its above tat, then this might help

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Include this before your HTTP connection creation; Then it works




回答5:


From Honeycomb SDK (3), Google will no longer allow network requests (HTTP, Socket) and other related operations directly in the Main Thread class, in fact, should not do direct network operation in the UI thread, blocking UI, user experience is bad! Even if Google is not prohibited, under normal circumstances, we will not do it ~! So, that is, in the Honeycomb SDK (3) version, you can also continue to do so in Main Thread, more than 3, it will not work.

1.use Handler

The more time-consuming operations associated with network are placed into a child thread and then communicated with the main thread using the Handler messaging mechanism

public static final String TAG = "NetWorkException";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_net_work_exception);
    // Opens a child thread, performs network operations, waits for a return result, and uses handler to notify UI
    new Thread(networkTask).start();
}

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // get data from msg and notify UI
        Bundle data = msg.getData();
        String val = data.getString("data");
        Log.i(TAG, "the result-->" + val);
    }
};

/**
 * net work task
 */
Runnable networkTask = new Runnable() {

    @Override
    public void run() {
        // do here, the HTTP request. network requests related operations
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("data", "request");
        msg.setData(data);
        handler.sendMessage(msg);
    }
};

2.use AsyncTask

public static final String TAG = "NetWorkException";
private ImageView mImageView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_net_work_exception);
    mImageView = findViewById(R.id.image_view);
    new DownImage(mImageView).execute();
}


class DownImage extends AsyncTask<String, Integer, Bitmap> {

    private ImageView imageView;

    public DownImage(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        String url = params[0];
        Bitmap bitmap = null;
        try {
            //load image from internet , http request here
            InputStream is = new URL(url).openStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // nodify UI here
        imageView.setImageBitmap(result);
    }
}

3.use StrictMode

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}


来源:https://stackoverflow.com/questions/5150637/networkonmainthreadexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!