【发布时间】:2019-03-20 16:16:47
【问题描述】:
我尝试创建同步线程,但总是出现以下错误:android.os.NetworkOnMainThreadException。
我阅读了更多帖子,但它们对我不起作用。
下面我写了对我不起作用的代码块:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
@Override
public void run () {
synchronized (syncJob) {
String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
txtState.setText (s);
}}});
}
});
t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
同步应用:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
我需要调用一个线程,等待答案并调用另一个线程。他们的答案我必须在活动中使用它们
【问题讨论】:
-
您也可以使用 CountDownLatch 来等待异步进程。 docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
标签: android multithreading synchronized ui-thread android-runonuithread