来自A线程的Android调用活动B的方法

时间:2012-11-24 05:51:02

标签: android multithreading user-interface android-activity

我有一个主要的Activity A,我在其中创建一个后台线程来从db加载数据。加载完成后,我想更新可能已经在子活动B中显示的列表(如果用户同时导航到B)。如果用户尚未导航到B,则不是问题。

但是一旦A中的线程完成后如何更新B的列表?

B是A的孩子。

谢谢,

2 个答案:

答案 0 :(得分:0)

首先将列表设置为空。您可以将用户带到活动B.存储列表数据的内容并使用静态列表填充列表,该列表在后台线程不完整时为空。从db完成加载后,调用列表适配器的notifydatasetchanged()方法。

实现后台线程的简单方法是异步任务。您可以通过覆盖相应的方法来定义异步任务的不同阶段。

答案 1 :(得分:0)

谢谢伊姆兰,

我通过在一个单独的类中创建一个IntentService来处理它(内部类没有工作),然后从A开始它。完成工作后,我从B的broadcastreceiver正在侦听的IntentService中激活一个BroadCast。它最终会更新列表。

以下是代码:

在A类中,只需在ex OnCreate()中启动IntentService:

Intent contactIntent = new Intent(this, ContactLoaderService.class);
        startService(contactIntent);    

创建类似(在单独的类中)的IntentService:

public class ContactLoaderService extends IntentService {
    public ContactLoaderService() {
        super("ContactLoaderService");
    }

    @Override
    protected void onHandleIntent(Intent arg0)
    {
        populateContacts();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(ContactsResponseReceiver.ACTION_RESP);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        sendBroadcast(broadcastIntent);
    }
}

在B类中,我创建了一个内部类,它只是更新列表,如:

public class ContactsResponseReceiver extends BroadcastReceiver {
    public static final String ACTION_RESP = "com.a.b.c.ContactsLoaded";

    @Override
    public void onReceive(Context context, Intent intent) {
        mCurrentAdapter.notifyDataSetChanged();
    }
}

在B中,不要忘记注册接收器。在B的onCreate()方法中:

IntentFilter filter = new IntentFilter(ContactsResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ContactsResponseReceiver();
registerReceiver(receiver, filter);

AndroidManifest.xml中常用的服务标签

<service android:name="com.a.b.c.ContactLoaderService"> </service>
相关问题