【问题标题】:Android call activity B's method from A's threadAndroid 从 A 的线程调用活动 B 的方法
【发布时间】:2012-11-24 05:51:01
【问题描述】:

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

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

B 是 A 的孩子。

谢谢,

【问题讨论】:

  • 您需要将数据加载部分从 Activity 分离到 IntentService 并注册一个 Broadcastreciver 以在从 Intentservice 完全加载数据时通知 Activity
  • @EdwardSullen,还没有找到任何东西。
  • @imran,我会尝试,但没有更简单的解决方案?
  • @droidbee :我认为广播接收器是解决当前问题的唯一方法。但您也可以尝试在活动 B 中使用 SheredPreferences 或额外的线程
  • @imrankhan,我实现了 IntentService 的解决方案。我的 bg 加载东西需要查询 db,所以我需要一个 Context。如果我将 IntentService 作为内部类,它永远不会运行。如果我把它变成一个单独的类,如何在那里有上下文? getApplicationContext() 不起作用。谢谢。

标签: android multithreading user-interface android-activity


【解决方案1】:

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

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

【讨论】:

  • 重点是如何获取父Activity发起的Thread中子Activity的引用?只有这样我才能调用 notifydatasetchanged()。
  • 我认为最初你有一些内容可以填满列表。假设您将其添加到 List 。为带子活动的 buttonclick 事件保留一个布尔标志。如果标志为 true ,则调用 notifydatasetchanged(delcare 关联为静态的适配器),如果为 false 则不要调用 。在任何一种情况下,您都会更新已添加初始内容的列表,该列表再次必须是静态列表。
  • 并且标志的检查应该在对应于线程完成的事件中。
【解决方案2】:

感谢伊姆兰,

我通过在一个单独的类中创建一个 IntentService 来处理它(内部类不工作),然后从 A 启动它。工作完成后,我从 B 的广播接收器正在侦听的 IntentService 发射一个广播。它最终会更新列表。

代码如下:

在 A 类中,只需在 for 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-12
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多