如何从线程中获取字符串或从线程返回String?

时间:2015-07-05 01:08:38

标签: java android java-threads

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

4 个答案:

答案 0 :(得分:2)

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

}

答案 1 :(得分:1)

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

以下是活动代码

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 

        }
    };

}

这里是下载String或其他任何

的线程的代码
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。

答案 2 :(得分:0)

  • 使用从主线程创建的Handler。然后传递你的数据
  • 在您的帖子中使用您的活动的弱引用;这样你就可以直接调用主线程 - 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
            }
        });
    }
    

答案 3 :(得分:0)

您可以使用异步任务:

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
   }
}