Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 意向服务中的静态块引发NetworkOnMainThreadException_Android_Static_Intentservice - Fatal编程技术网

Android 意向服务中的静态块引发NetworkOnMainThreadException

Android 意向服务中的静态块引发NetworkOnMainThreadException,android,static,intentservice,Android,Static,Intentservice,创建了一个IntentService,其中我创建了一个静态块,在该块中我正在做一些与网络相关的工作,它在该块上给出了networkonmainthreadeception: 代码类似于: public class XService extends IntentService { static { //Net related work //on executing this gives NetworkOnMainThreadException }

创建了一个
IntentService
,其中我创建了一个静态块,在该块中我正在做一些与网络相关的工作,它在该块上给出了
networkonmainthreadeception
代码类似于:

public class XService extends IntentService {
    static {
        //Net related work 
        //on executing this gives NetworkOnMainThreadException
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //Doing my work here
    }   
}
IntentSrevice
在单独的线程上运行时,该
如何引发NetworkOnMainThreadException


请提前帮助和感谢。

发生这种情况是因为您正在主线程上执行网络操作,而Android 3.0及以上版本不允许这样做。即使服务在服务中,服务也会在UI线程上运行,除非您在另一个线程中专门启动它们或在其中创建线程

您可以通过使用线程或
AsyncTask
在主UI线程之外的服务中运行任务来修复此问题

尝试在
onStartCommand()

或者你可以做一些像

new Handler().post(new Runnable() { 
@Override public void run() {
 getData(); 
} });

您应该在
OnHandleIntent()
内完成与网络相关的工作,因为此方法在单独的线程上运行

与网络相关的工作现在在主线程上运行。

只有onHandleIntent()回调在后台线程上运行。