[英]How to pass the object back to Main thread from another threads in Android?
I have a fragment in which I start the thread. 我有一个片段在其中启动线程。 In this thread I get a object and after that I want to pass the object to the main thread.
在此线程中,我得到一个对象,然后将对象传递给主线程。 What shall I do for this?
我该怎么办?
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();
}}
I need to pass jsonObj back to the main thread? 我需要将jsonObj返回主线程吗?
you can try using the Join method in Thread. 您可以尝试在Thread中使用Join方法。 Other way you can do this also in a multi-threading program is to Synchronized the Object with you want to share between Threads.
您也可以在多线程程序中执行此操作的另一种方法是,使对象与您要在线程之间共享的对象同步。 by synchronizing the object , you must then first allow other thread that will finished manupulating the Object to have access first, and you will now later assign the object back to the main thread.
通过同步对象,必须首先允许其他将完成对对象的操作的线程首先具有访问权限,然后您现在将对象分配回主线程。 in this case if the current Thread handling the Object is not yet through with the Object any attempt by other thread will result into a wait.
在这种情况下,如果当前处理该对象的线程尚未通过该对象,则其他线程的任何尝试都将导致等待。 But when the Current Thread is through handling the object, Other thread can now have access to it
但是当当前线程通过处理对象时,其他线程现在可以访问它
Use interface to send object as call back. 使用接口发送对象作为回调。
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.