我有两个活动,ActivityA 和 ActivityB。ActivityA 启动一个长时间运行的进程(例如,在网络上检索数据)。在任何时候,用户都可以决定转到 ActivityB。一旦长时间运行的进程结束,它的结果应该显示在 ActivityA 或 ActivityB 中,以当时处于活动状态的为准。
为了实现这一点,我在 ActivityA 中创建了一个工作线程,并且 ActivityA 和 ActivityB 都依赖于 aLocalBroadcastManager
来获得长时间运行进程结束的通知并获取其结果。
这个实现似乎有效,但我想知道我是否遗漏了一些极端情况。在 SO 上,我看到关于和的讨论IntentService
,所以我担心我的方法可能过于幼稚。我这样做是正确的方式吗?如果没有,我错过了什么?AsyncTask
HandlerThread
这里有一些代码片段来说明我的问题。
活动A
public class ActivityA extends Activity {
public static final String BROADCAST_MESSAGE = "spike.workerthread.event.resultReady";
public static final String RESULT_KEY = "spike.workerthread.result";
private LocalBroadcastManager localBroadcastMgr;
private BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
localBroadcastMgr = LocalBroadcastManager.
getInstance(getApplicationContext());
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView resultTextView = (TextView) findViewById(R.id.result);
resultTextView.setText(intent.getStringExtra(RESULT_KEY));
}};
localBroadcastMgr.registerReceiver(receiver,
new IntentFilter(BROADCAST_MESSAGE));
}
public void startFetchingResultFrom(final ResultProvider provider) {
Thread thread = new Thread() {
@Override
public void run() {
String result = provider.getResult(); // Can take a long time...
Intent intent = new Intent(BROADCAST_MESSAGE);
intent.putExtra(RESULT_KEY, result);
localBroadcastMgr.sendBroadcast(intent);
}
};
thread.start();
}
public void startActivityB() {
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
startActivity(intent);
}
}
活动B
public class ActivityB extends Activity {
private LocalBroadcastManager localBroadcastMgr;
private BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
localBroadcastMgr = LocalBroadcastManager.getInstance(getApplicationContext());
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView resultTextView = (TextView) findViewById(R.id.result);
resultTextView.setText(intent.getStringExtra(ActivityA.RESULT_KEY));
}};
localBroadcastMgr.registerReceiver(receiver, new IntentFilter(ActivityA.BROADCAST_MESSAGE));
}
}