2016-09-21 54 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

相關問題