NetworknMainThreadException在Runnable上 [英] NetworkOnMainThreadException on Runnable

查看:127
本文介绍了NetworknMainThreadException在Runnable上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Android 4.4项目.我有NetworkOnMainThreadException. 下面是我的过程.

I am making Android 4.4 project. I've got NetworkOnMainThreadException. Below is my process.

Service(sticky) -> Handler(per 5 minutes) -> Runnable -> HttpPost

不是可以运行一个单独的线程吗?我应该在Runnable中使用AsyncTask吗?

Isn't Runnable a separate thread? Shoud I use AsyncTask in Runnable?

推荐答案

Runnable是一个简单的界面,即应由其实例打算由线程执行的任何类实现". (强调我的.)

Runnable is a simple interface, that, as per the Java documentation, "should be implemented by any class whose instances are intended to be executed by a thread." (Emphasis mine.)

例如,按如下所示定义Runnable只会在与创建它相同的线程中执行它:

For instance, defining a Runnable as follows will simply execute it in the same thread as it's created:

new Runnable() {
    @Override
    public void run() {
        Log.d("Runnable", "Hello, world!");
    }
}.run();

观察到您实际上在这里所做的只是创建一个类并执行其公共方法run().这里没有使它在单独的线程中运行的魔术.当然没有; Runnable只是一个三行的接口代码

Observe that all you're actually doing here is creating a class and executing its public method run(). There's no magic here that makes it run in a separate thread. Of course there isn't; Runnable is just an interface of three lines of code!

将其与实现线程(实现Runnable)进行比较:

Compare this to implementing a Thread (which implements Runnable):

new Thread() {
    @Override
    public void run() {
        Log.d("Runnable", "Hello, world!");
    }
}.start();

此处的主要区别在于Thread的start()方法负责生成新线程并在其中执行Runnable的run()的逻辑.

The primary difference here is that Thread's start() method takes care of the logic for spawning a new thread and executing the Runnable's run() inside it.

Android的AsyncTask进一步促进了线程执行和对主线程的回调,但是概念是相同的.

Android's AsyncTask further facilitates thread execution and callbacks onto the main thread, but the concept is the same.

这篇关于NetworknMainThreadException在Runnable上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆