2016-09-21 86 views
0

我有一个片段,我开始线程。在这个线程中,我得到一个对象,然后我想将对象传递给主线程。我应该为此做些什么?如何将对象从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传递回主线程?

+0

http://stackoverflow.com/questions/11140285/how-to-use-runonuithread –

回答

-1

使用接口发送对象作为回调。

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); 
} 
0

您可以尝试使用Thread中的Join方法。在多线程程序中也可以这样做的其他方法是将对象与想要在线程之间共享的对象同步。通过同步对象,您必须首先允许其他线程完成Manupulation对象的访问,然后您将稍后将对象分配回主线程。在这种情况下,如果当前的线程处理对象还没有通过对象,其他线程的任何尝试都将导致等待。但是当当前线程是通过处理对象,其他线程现在可以访问它

+0

但是,如果我使用mHandler。 sendMessage(mHandler.obtainMessage(what,2,0,jsonObj.toString()));然后获取对象使用msg.getData()。getString()?这将是正确的? – Delphian

相关问题