我正在使用获取数据并存储在String
. 我需要使用它String
,但我不能接受。全局变量在线程中不起作用。我正在使用传统的 Thread new Thread() { public void run() {
。
问问题
122 次
4 回答
2
异步任务示例:
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);
}
}
于 2015-07-05T01:19:17.390 回答
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
}
};
}
这里是下载字符串或其他线程的代码
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。
于 2015-07-05T01:22:32.020 回答
0
- 使用从主线程创建的处理程序。然后通过它传递你的数据
在您的线程中使用您的活动的弱引用;这样就可以直接调用主线程——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 } }); }
于 2015-07-05T01:15:45.970 回答
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
}
}
于 2015-07-05T01:36:02.727 回答