简体   繁体   中英

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:

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.

What is the problem?

I tried using runOnUiThread() and using Handler but nothing changes.

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. If you have potentially long running operations, you should trigger a service instead.

Since Android API 11 you can call the goAsync() method. This method returns an object of the PendingResult type. The Android system considers the receiver as alive until you call the PendingResult.finish() on this object. 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.

I highly recommend you follow this tutorial through as it will make you understand how do these work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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