您好我正在使用服务从本地教程中加载来自网址的数据(Background Service Tutorial)。
我有2项活动。第一个用于启动Activity,启动服务,第二个用于启动服务。当我从第二个活动开始服务并在那里等待服务完成时,ui组件会正确更新。
但是当我从第二个Activity启动服务时,完成它并再次启动第二个活动,UI组件在服务完成时不会更新。但是获取的数据正确地正确地进入onReceiveResult,只是UI视图没有得到更新。
为什么会这样?我怎样才能解决这个问题?
我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Allow activity to show indeterminate progressbar */
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_my);
btnStartserv=(Button)findViewById(R.id.buttonserv);
/* Initialize listView */
//listView = (ListView) findViewById(R.id.listView);
/* Starting Download Service */
mReceiver = new DownloadResultReceiver(new Handler());
mReceiver.setReceiver(MyActivity.this);
btnStartserv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MyActivity.this,"Service Started",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_SYNC, null, MyActivity.this, DownloadService.class);
/* Send optional extras to Download IntentService */
intent.putExtra("url", url);
intent.putExtra("receiver", mReceiver);
intent.putExtra("requestId", 101);
startService(intent);
}
});
}
onReceiveResult:
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
switch (resultCode) {
case DownloadService.STATUS_RUNNING:
setProgressBarIndeterminateVisibility(true);
break;
case DownloadService.STATUS_FINISHED:
setContentView(R.layout.activity_my);
Toast.makeText(MyActivity.this,"Service Finished",Toast.LENGTH_SHORT).show();
/* Hide progress & extract result from bundle */
setProgressBarIndeterminateVisibility(false);
String[] results = resultData.getStringArray("result");
System.out.println("size"+results.length);
listView = (ListView) findViewById(R.id.listView);
if(listView == null ){
System.out.println("listview is null");
}else{
System.out.println("listview is NOT NULL");
}
btnStartserv=(Button)findViewById(R.id.buttonserv);
btnStartserv.setText("Service Finished!!!");
/* Update ListView with result */
arrayAdapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_1, results);
listView.setAdapter(arrayAdapter);
break;
case DownloadService.STATUS_ERROR:
/* Handle the error */
String error = resultData.getString(Intent.EXTRA_TEXT);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
break;
}
}
修改:添加了DownloadResultReceiver类
DownloadResultReceiver:
public class DownloadResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public DownloadResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}