LocalBroadcastManager vs Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver() are they same?

前端 未结 1 1107
臣服心动
臣服心动 2021-01-31 03:15

I was using Context.registerReceiver(), Context.sendBroadcast(Intent) , and Context.unregisterReceiver()

but when I saw the class LocalBroadcastManag

1条回答
  •  余生分开走
    2021-01-31 03:48

    LocalBroadcastManager is as its name says, an implementation of the broadcast methods that are only available to your app. This has some benefits, with the biggest being safety, one less hole to watch out for. In terms of implementation, there are a few things to keep in mind:

    • This class is from the Android Support Library
    • The method calls have to be prefaced with LocalBroadcastManager.getInstance([CONTEXT]) where [CONTEXT] is a subclass of the Context class, such as Activity.
    • When you use this class, it is purely for your app. Using it to register receivers and make broadcasts that are system wide will fail.

    So this class is not the same as Context, it is simply a very specific, app-only implementation of Context's receiver/broadcast methods. You should use it when there is absolutely no point for your listener to listen on global (system-wide) broadcasts and when your broadcast does not need to target anything outside your app.

    0 讨论(0)
提交回复
热议问题