我只想问,对于我来说,解决以下问题的最佳方法是什么。情况是这样的。
1)我有活动A和活动B。
2.)用户在activitya中处理某个东西(asynctask),现在当用户正在等待时,他转到了activityb。
3.)因此,当用户在activityb中时,任务在activitya中成功完成。我如何通知activityb任务已经完成
在活动中完成?
最佳答案
您可以使用LocalBroadcastManager。当您在activitya中的异步任务完成时。
发送ActivityB可以接收的BroasCast。然后activityb就会知道任务已经完成了。
活动a:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ActivityA.this,ActivityB.class));
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
//do some long work
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent("ACTION_TASK_DONE"));
}
}.execute();
}
});
}
活动B:
private BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(ActivityB.this,"Task done!" , Toast.LENGTH_SHORT).show();
}
};
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(broadcastReceiver, new IntentFilter("ACTION_TASK_DONE"));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (broadcastReceiver != null) {
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(broadcastReceiver);
}
}