[英]How to pass the object back to Main thread from another threads in Android?
我有一个片段在其中启动线程。 在此线程中,我得到一个对象,然后将对象传递给主线程。 我该怎么办?
public class IFragment extends Fragment {
private void getRecentlyTag(){
new Thread(){
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Constants.API_URL);
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Tools.streamToString(urlConnection
.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response)
.nextValue();
}catch(Exception exc){
exc.printStackTrace();
}finally {
if(urlConnection!=null){
try{
urlConnection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}
// mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}}
我需要将jsonObj返回主线程吗?
您可以尝试在Thread中使用Join方法。 您也可以在多线程程序中执行此操作的另一种方法是,使对象与您要在线程之间共享的对象同步。 通过同步对象,必须首先允许其他将完成对对象的操作的线程首先具有访问权限,然后您现在将对象分配回主线程。 在这种情况下,如果当前处理该对象的线程尚未通过该对象,则其他线程的任何尝试都将导致等待。 但是当当前线程通过处理对象时,其他线程现在可以访问它
使用接口发送对象作为回调。
private void getRecentlyTag(final OnResponseListener listener){
new Thread(){
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Constants.API_URL);
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Tools.streamToString(urlConnection
.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response)
.nextValue();
if(listener!=null){
listener.onResponseReceived(jsonObj);
}
}catch(Exception exc){
exc.printStackTrace();
}finally {
if(urlConnection!=null){
try{
urlConnection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}
// mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
} }
interface OnResponseListener{
void onResponseReceived(JSONObject obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.