我在活动A中启动异步任务,并立即启动活动B.完成活动A中的后台任务后,我想更新活动B的UI。以下是代码的原型:
public class ActivityA extends Activity{
public void onCreate() {
// Starting asynctask here
BackgroundAsyncTask mBackgroundObject=new BacgroundAsyncTask(getActivity.getApplicationContext());
mBackgroundObject.execute();
// Start Activity B
}
public class BackGroundAsyncTask extends AsyncTask< ... > {
Context context;
public BackGroundAsyncTask(Context mCOntext){
context = mContext;
}
doInBackground(){
// Background Task
}
onPostExecute(){
ActivityB.UpdateUI(context);
}
}
}
public class ActivityB extends Activity {
public void onCreate(){}
public static void UpdateUI(Context mContext) {
// **Here I want to update the UI of Activity B , but it is not happening, looks like it is because context is of activity A**
}
}
任何有关回调侦听器或任何其他实现的实现方面的帮助都会有很大的帮助。我面临的问题是我没有得到任何例外,但活动B的UI没有得到更新。
答案 0 :(得分:0)
从异步任务创建回调
从异步任务获取结果后,将更新的数据从活动A发送到活动B vai广播意图
在活动B中注册本地BroadcastReceiver
在广播监听器的onReceive()
方法中,您可以获得所有更新的数据vai意图更新您的UI
或
直接从onPostExecute()
方法发送广播
答案 1 :(得分:0)
我在这里放了一个小的演示,它与上面的相同。
public class TestA extends Activity{
private final String ACTION_NAME = "bc";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(5000);
Intent mIntent = new Intent(ACTION_NAME);
mIntent.putExtra("yaner", "发送广播,相当于在这里传送数据");
//发送广播
sendBroadcast(mIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
startActivity(new Intent(this, TestB.class));
}
}
public class TestB extends Activity{
private final String ACTION_NAME = "bc";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//注册广播
registerBoradcastReceiver();
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ACTION_NAME)){
Log.d("aaa", "TestB onReceive:"+intent.getStringExtra("yaner"));
}
}
};
public void registerBoradcastReceiver(){
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(ACTION_NAME);
//注册广播
registerReceiver(mBroadcastReceiver, myIntentFilter);
}
}