【发布时间】:2017-07-31 11:36:06
【问题描述】:
当您在 Android 中建立网络连接时,您会阻塞主线程,因此您必须将此任务的“部分”移动到新线程
关于这部分我有 2 个问题
1- 以下哪个操作阻塞了主线程(A 或 B)
//A:
HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection();
//B:
InputStream stream=c.getInputStream();
2- 如果上述(A 和 B)中的“两者”都必须在新线程中运行,那么在新的单独线程中运行每个线程是否会产生不良影响?看看下面的代码:
//I temporary removed try & catch to simplify the code
public class connect{
HttpURLConnection c; String url;
public connect(String url){
this.url=url;
new Thread(new Runnable{
@override public void run(){
c = (HttpURLConnection) (new URL(url)).openConnection();
}
});
}
public InputStream get(){
return c.getInputStream();
//or make this one in a new thread
}
public InputStream post(Sring params){
c.setRequestMethod("POST");
//.. make some code for posting data , and then call get()
//thats why i cannot perform c.getInputStram() at the same time with openConnection()
return get()
}
}
【问题讨论】:
标签: android multithreading android-asynctask internet-connection