在我的 Android 应用程序中,我有一个带有适配器的简单 ListView 。有一个繁重的查询是用数据填充 ListView 。所以我把它放到另一个线程中运行的 IntentService 中。
IntentService 通常单独运行,单独运行,只是为了查询一些数据并将其插入 SQLite 数据库。
但现在我想有以下可能:
- Activity 使用 startService() 启动 IntentService。
- IntentService 完成了繁重的工作。
- IntentService 完成后,应将结果通知 Activity,以便刷新 Activity 以显示新数据。
这可能吗?我在 Stack Overflow 上阅读了很多关于这个主题的问题。但在每一个问题中,都有另一种解决方案。所以我想问大家:哪种解决方案最适合我的目的?
- 将 IntentService 绑定(bind)到 Activity 似乎不是最好的解决方案,因为可能会与 Activity 的配置更改等发生冲突。对吗?
- This blog post建议将 AIDL 与 Parcelables 一起使用——这对我来说听起来很复杂。有更简单的方法,不是吗?
- 可以在 Activity 中设置广播接收器,并在完成后在 IntentService 中触发此广播。
- 有人说你应该use createPendingResult() to pass a PendingIntent到 IntentService。如果 IntentService 在其 extras 中发现 PendingIntent,它会使用它来触发 Activity 中的 onActivityResult()。这是选择的方式吗?
最佳答案
例如,我使用 ResultReceiver在我的 Activity
(扩展 ListActivity
)的适配器上调用 notifyDataSetChanged()
。它可以适应你需要的任何东西。
ResultReceiver 代码:
public class MyResultReceiver extends ResultReceiver {
private Context context = null;
protected void setParentContext (Context context) {
this.context = context;
}
public MyResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult (int resultCode, Bundle resultData) {
// Code to process resultData here
((BaseAdapter) ((ListActivity)context).getListAdapter()).notifyDataSetChanged();
}
}
我的 Activity 代码:
public class MyActivity extends ListActivity {
private MyResultReceiver theReceiver = null;
...
private void callService () {
theReceiver = new MyResultReceiver(new Handler());
theReceiver.setParentContext(this);
Intent i = new Intent("com.mycompany.ACTION_DO_SOMETHING");
// Code to define and initialize myData here
i.putExtra("someData", myData);
i.putExtra("resReceiver", theReceiver);
startService(i);
}
}
IntentService 代码:
Bundle resultBundle = new Bundle();
ResultReceiver resRec = intent.getParcelableExtra("resReceiver");
// Do some work then put some stuff in resultBundle here
resRec.send(12345, resultBundle);
关于android - 从 Activity 启动 IntentService 并在 IntentService 完成时刷新 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088315/