网络主线程异常

发布于 2024-10-19 19:34:29 字数 432 浏览 3 评论 0原文

我刚刚在官方文档中发现了 NetworkOnMainThreadException

并且想知道模拟器是否会抛出此异常。我已经对我的应用程序进行了相当多的测试,据我所知,所有网络都脱离了主线程(使用 Roboguice RoboAsyncTask),但你永远不知道是否有一个网络没有逃脱。

我也在使用 StrictMode,但没有看到任何东西。

  1. 我的代码是干净的还是没有抛出到模拟器上?

  2. 我们应该如何为生产中发生的这种情况做好准备?

  3. 宽限期之类的怎么样? 或者现在已经过去了;-) ??

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 ;-) ??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

極樂鬼 2024-10-26 19:34:29

使用 Honeycomb,您无法按照文档所述在其主线程上执行网络操作。因此,您必须使用 handler 或 asynctask。没有其他方法可以做到这一点。

在这里您可以找到 2 个用土耳其语编写的有关网络操作的示例。也许他们有帮助。

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.

情释 2024-10-26 19:34:29

我已经对此进行了测试,实际上它也发生在模拟器上。如果您计划将应用程序移植到 3.0 及更高版本的平板电脑上,最好确保至少在模拟器上测试您的应用程序。

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.

清风夜微凉 2024-10-26 19:34:29

NetworkOnMainThreadException 在 main 方法内部执行某些网络操作时发生;我的意思是Oncreate()。您可以使用AsyncTask来解决此问题。或者您可以使用

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

内部 onCreate() 方法。

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.

独享拥抱 2024-10-26 19:34:29

如果你运行的是 3.0,我无能为力;因为里面默认是开启严格模式的;但它是上面的内容,那么这可能会有所帮助

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

在创建 HTTP 连接之前包含此内容;然后就可以了

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

半衾梦 2024-10-26 19:34:29

从Honeycomb SDK(3)开始,Google将不再允许在Main Thread类中直接进行网络请求(HTTP、Socket)等相关操作,实际上不应该在UI线程中直接进行网络操作,阻塞UI,用户体验很差坏的!即使Google不禁止,一般情况下,我们也不会这么做~!
所以,也就是说,在Honeycomb SDK(3)版本中,还可以在Main Thread中继续这样做,超过3,就不行了。

1.使用Handler

将与网络相关的比较耗时的操作放到子线程中,然后使用Handler与主线程通信消息传递机制

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.使用 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.使用 StrictMode

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文