NetworkOnMainThreadException on Runnable

可紊 提交于 2019-12-20 07:24:12

问题


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

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

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


回答1:


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.)

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

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!

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

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

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's AsyncTask further facilitates thread execution and callbacks onto the main thread, but the concept is the same.




回答2:


Runnable just per se is not a Thread. You can use a Runnable to be run inside a Thread, but these are different concepts. You can use an AsyncTask or just define a Thread and use .start() over it.



来源:https://stackoverflow.com/questions/22580354/networkonmainthreadexception-on-runnable

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