简体   繁体   English

从广播接收机调用的更新列表视图的方法无效

[英]Method to update list view called from broadcast receiver does not work

I encountered a problem when implementing broadcast receiver. 在实现广播接收器时遇到了一个问题。

I have this function inside Fragment class: 我在Fragment类中具有以下功能:

public void reloadMessages() {
    List<SmsList> values = smsToSmsList(getAllSms());
    mPostAdapter.clear();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mPostAdapter.addAll(values);
    } else {
        for (SmsList smsList : values) {
            mPostAdapter.add(smsList);
        }
    }
    mPostAdapter.notifyDataSetChanged();
    Log.d(null, "reloadMessages");
}

and I call it from broadcast receiver: 我从广播接收器调用它:

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

                mainFragment.reloadMessages();

        Log.d("myactivity", "broadcast received");
    }
};

Analyzing with debugger shows that this function is called properly, but nothing happens. 使用调试器进行分析表明,此函数已正确调用,但没有任何反应。 I performed a test and called that function from onclick function and it works properly. 我执行了一个测试,并从onclick函数中调用了该函数,它可以正常工作。

What is the problem? 问题是什么?

I tried using runOnUiThread() and using Handler but nothing changes. 我尝试使用runOnUiThread()和Handler,但没有任何变化。

Before API level 11, you could not perform any asynchronous operation in the onReceive() method, because once the onReceive() method had been finished, the Android system was allowed to recycle that component. 在API级别11之前,您无法在onReceive()方法中执行任何异步操作,因为一旦完成onReceive()方法,便允许Android系统回收该组件。 If you have potentially long running operations, you should trigger a service instead. 如果您的操作可能长期运行,则应改为触发服务。

Since Android API 11 you can call the goAsync() method. 从Android API 11开始,您可以调用goAsync()方法。 This method returns an object of the PendingResult type. 此方法返回PendingResult类型的对象。 The Android system considers the receiver as alive until you call the PendingResult.finish() on this object. 在您对此对象调用PendingResult.finish()之前,Android系统会将接收器视为处于活动状态。 With this option you can trigger asynchronous processing in a receiver. 使用此选项,您可以在接收器中触发异步处理。

What you need to do instead is to start a service which will perform such operation whenever the event is broadcast: 您需要做的是启动一个服务,该服务将在事件广播时执行以下操作:

new BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) { 
    Intent intent = new Intent(context, CustomService.class);
    context.startService(intent);
  }
} 

EDIT : 编辑:

You may be missing something about the matter, such as correctly declaring xml components and permissions regarding broadcast receiving and services. 您可能缺少有关此事的信息,例如正确声明了xml组件以及有关广播接收和服务的权限。

I highly recommend you follow this tutorial through as it will make you understand how do these work. 我强烈建议您按照教程进行操作,因为它将使您了解这些工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM