//在子线程中使用 runOnUiThread 在UI线程执行 runOnUiThread()
runOnUiThread(updateThread);
Runnable updateThread = new Runnable()
{
@Override
public void run()
{
}
};
示例:
new Thread(new Runnable() {
@Override
public void run() {
String url = "url";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try{
JSONArray jsonArray=new JSONArray(response.body().string());
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
Integer id=jsonObject.getInt("id");
ProjectList.add(new Project(id));
}
WorkbenchActivity.this.runOnUiThread(updateThread);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
};
Runnable updateThread = new Runnable()
{
@Override
public void run()
{
if (ProjectList != null) {
ProjectAdapter adapter=new ProjectAdapter(WorkbenchActivity.this,R.layout.project_list_item,ProjectList);
listView.setAdapter(adapter);
} else {
System.out.println("数据错误!");
}
}
};
|