我创建了一系列与服务器相关的操作,并将它们放在一个名为
OutgoingSync.java我没有围绕任何网络操作包装任何线程。
这就是我开始整个事情的方式。
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(new Runnable() {
@Override
public void run() {
new OutgoingSync(context);
}
});我使用ExecutorService是因为我想让它帮我关闭线程,所以我不必担心这一点。
但是,当第一个网络操作开始时,我得到了一个NetworkOnMainThread异常。
下面是一个代码片段:
public class OutoingSync {
public OutgoingSync(Context context){
Log.e("OutgoingSync thread", Thread.currentThread.getName()); // Output "pool-2,thread-1"
doSomeStuff();
}
private void doSomeStuff() {
new UploadPhotosToServer();
}
}
public class UploadPhotosToServer {
public UploadPhotosToServer() {
Log.e("Upload photos thread", Thread.currentThread.getName()); // Output is "main"
// And the following network-related code throws a NetworkOnMainThreadException (because it is run on the main thread)
}
}发布于 2015-05-31 20:59:45
从文档中
当应用程序尝试在其主线程上执行网络操作时引发的异常
因此,您可以尝试在AsyncTask中运行代码。它的executeOnExecutor()方法可以做到这一点。
http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)
发布于 2015-05-31 23:32:44
您使用submit方法但未执行的问题。因此,你仍然在主线上。
提交
提交要执行的Runnable任务,并返回表示该任务的Future。Future的get方法将在成功完成后返回给定的结果。
执行
在将来的某个时间执行给定的命令。根据执行器实现的判断,该命令可以在新线程、池化线程或调用线程中执行。
来自ExecuterService和Executer
https://stackoverflow.com/questions/30557528
复制相似问题