如何从线程中获取字符串或从线程中获取 return 字符串?

How do I get a string from a thread or return a String form a Thread?

我正在使用获取数据并存储在 String 中的网络服务。我需要使用这个 String 但我不能接受。全局变量在线程中不起作用。我使用的是传统线程 new Thread() { public void run() {.

  • 使用从主线程创建的处理程序。然后通过它传递你的数据
  • 在您的主题中使用您的 activity 的弱引用;这样你就可以直接调用主线程 - Activity.runOnUiThread(Runnable)

    ...
    Activity activity = activityWeakReference.get();
    if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
                // you are in main thread, pass your data
            }
        });
    }
    

AsyncTask 示例:

public class Task extends AsyncTask<Params, Progress, String> {
     // are you know how to use generic types?

     protected String doInBackground(Params[] params){
           // this code will run in seperate thread
           String resultString;
           return resultString;
     }
     protected void onPostExecute(String resultString){
           // this code will call on main thread (UI Thread) in this thread you can update UI e.g. textView.setText(resultString);
     }

}

使用 LocalBroadcastManager 发送和接收数据。 这样可以避免内存泄漏问题。

这是 activity

的代码
public class YourActivity extends Activity {

    private void signal(){
        LocalBroadcastManager.getInstance(YourActivity.this).registerReceiver(receiver, new IntentFilter("Your action name"));
        Intent yourAction = new Intent(YourActivity.this, YourIntentService.class);
        String string = "someData";
        yourAction .putExtra("KEY_WITH_URL", string);
        startService(yourAction);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String string = intent.getStringExtra("KEY_WITH_ANSWER");
            //Do your code 

        }
    };

}

这里是下载字符串或其他线程的代码

public class YourIntentService extends IntentService {

    @Override
    protected void onHandleIntent(Intent intent) {
        // Download here

        Intent complete = new Intent ("Your action name");
        complete.putExtra("KEY_WITH_ANSWER", stringToReturn);
        LocalBroadcastManager.getInstance(YourIntentService.this).sendBroadcast(complete);

    }

}

您可以使用 Thread 而不是 IntentService。

您可以使用异步任务:

private class Whatever extends AsyncTask<Void, Void, String> {
   protected String doInBackground(Void... void) {
       // do your webservice processing
       return your_string;
   }

   protected void onPostExecute(String result) {
       // Retrieves the string in the UI thread
   }
}