- Как проверить, зарегистрирован ли приемник на Android?
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- простейшее решение
- в приемнике:
- в коде:
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Local Broadcast, less overhead and secure in Android
- Basics of Broadcast
- Register Broadcast
- Receive Broadcasts
- Problem with global broadcast
- What is LocalBroadcastManager?
- Implementation
- How to secure broadcasts
- Restrict your app to receive broadcast
- Control receiver of your broadcast
- Conclusion
- How to check if Receiver is registered in Android?
- simplest solution
- in receiver:
- in code:
- Related Posts
- android – How do I display a CalendarView in an AlertDialog?
- How do I convert a PSD design to Android xml?
Как проверить, зарегистрирован ли приемник на Android?
Мне нужно проверить, зарегистрирован ли зарегистрированный ресивер, если нет, как проверить его какие-либо методы?
ОТВЕТЫ
Ответ 1
Я не уверен, что API предоставляет непосредственно API, если вы рассматриваете эту тему:
Я думал о том же самом.
В моем случае у меня есть реализация BroadcastReceiver которая вызывает Context#unregisterReceiver(BroadcastReceiver) передавая себя в качестве аргумента после обработки получаемого намерения.
Существует небольшая вероятность того, что метод приемника onReceive(Context, Intent) вызывается более одного раза, так как он зарегистрирован в нескольких IntentFilters , создавая возможность для IntentFilters IllegalArgumentException из Context#unregisterReceiver(BroadcastReceiver) .
В моем случае я могу сохранить частный синхронизированный элемент для проверки перед вызовом Context#unregisterReceiver(BroadcastReceiver) , но было бы намного чище, если бы API предоставил метод проверки.
Ответ 2
Нет функции API, чтобы проверить, зарегистрирован ли получатель. Обходной путь — поместить ваш код в блок try catch block as done below.
Ответ 3
простейшее решение
в приемнике:
в коде:
объявление 1
Это действительно не так уж и элегантно, потому что вы должны помнить, чтобы установить isRegistered флаг после регистрации. — Раввин Стелс
— «более элегантный способ» добавлен метод в приемнике для регистрации и установки флага
это не будет работать, если вы перезагрузите устройство или если ваше приложение было убито ОПЕРАЦИОННЫЕ СИСТЕМЫ. — Амин 6 часов назад
@amin — видеть время жизни зарегистрированного получателя в коде (а не в системе, зарегистрированной в декларации) 🙂
Ответ 4
Я использую это решение
Ответ 5
У вас есть несколько вариантов
Вы можете поместить флаг в свой класс или активность. Поместите логическую переменную в ваш класс и посмотрите на этот флаг, чтобы узнать, зарегистрирован ли ваш ресивер.
Создайте класс, который расширяет приемник и там вы можете использовать:
Шаблон Singleton имеет только один экземпляр этого класса в вашем проекте.
Внедрить методы, чтобы знать, зарегистрирован ли приемник.
Ответ 6
Вам нужно использовать try/catch:
Ответ 7
Вы можете сделать это легко.
1) создать логическую переменную.
2) Когда вы регистрируете свой широковещательный приемник, установите для него значение ИСТИНА
3) В onPause() сделайте это.
Только это, и теперь вы не получите больше сообщений об ошибке исключения на onPause().
Tip1: Всегда используйте unregisterReceiver() в onPause() не в onDestroy() Tip2: Не забудьте установить переменную bolBroadcastRegistred в FALSE при запуске unregisterReceive()
Ответ 8
Если вы положите это на метод onDestroy или onStop. Я думаю, что когда действие было создано снова, MessageReciver не создавался.
Ответ 9
Я использовал Intent, чтобы позволить Broadcast Receiver узнать о экземпляре Handler основного потока Activity и использовать Message для передачи сообщения в Main activity
Я использовал такой механизм, чтобы проверить, зарегистрирован ли широковещательный приемник или нет. Иногда это необходимо, когда вы регистрируете свой широковещательный приемник динамически и не хотите делать его дважды или вы представляете пользователю, если работает широковещательный приемник.
Ответ 10
Лично я использую метод вызова unregisterReceiver и проглатывает исключение, если оно было выбрано. Я согласен, что это уродливый, но лучший способ, который в настоящее время предоставляется.
Я поднял запрос функции, чтобы получить логический метод, чтобы проверить, добавлен ли ресивер в API Android. Пожалуйста, поддержите его здесь, если хотите добавить его: https://code.google.com/p/android/issues/detail?id=73718
Ответ 11
Я понял вашу проблему, я столкнулся с той же проблемой в моем приложении. Я вызывал registerReceiver() несколько раз в приложении.
Простое решение этой проблемы — вызвать registerReceiver() в вашем классе пользовательских приложений. Это гарантирует, что ваш приемник Broadcast будет вызываться только один на протяжении всего жизненного цикла приложения.
Ответ 12
Вот как я это сделал, это модифицированная версия ответа, данного ceph3us и отредактированная slinden77 (среди прочего я удалил возвращаемые значения методов, которые мне не нужны):
Затем в классе Activity:
Ответ 13
Я помещаю этот код в свою родительскую активность
Список зарегистрированныхReceivers = новый ArrayList ();
Ответ 14
Вот что я сделал, чтобы проверить, зарегистрирован ли Broadcaster, даже если вы закрываете приложение (finish())
Сначала запускайте приложение, сначала отправляйте широковещательную передачу, он вернет true/false, зависит от того, работает ли ваш вещатель или нет.
Ответ 15
Вы можете использовать Dagger, чтобы создать ссылку на этот приемник.
Сначала предоставьте это:
Затем вводят его там, где вам нужно ( с помощью constructor или поля injection )
и просто передайте его в registerReceiver .
Также поместите его в блок try/catch .
Ответ 16
Ответ 17
Просто проверьте исключение NullPointerException. Если приемник не существует, то.
Источник
Local Broadcast, less overhead and secure in Android
Apr 28, 2017 · 4 min read
Broadcast receiver is an Android component which allows you to send or receive Android system or application events. All the registered application are notified by the Android runtime once event happens.
It works similar to the publish-subscribe design pattern and used for asynchronous inter-process communication.
For example, applications can register for various system events like boot complete or battery low, and Android system sends broadcast when specific event occur. Any application can also create its own custom broadcasts.
Basics of Broadcast
Let’s discuss some basic concepts of broadcast receiver.
Register Broadcast
There are two ways to register broadcast receiver-
Manife s t-declared (Statically) : By this receiver can be registered via the AndroidManifest.xml file.
Context-registered (Dynamically) : By this register a receiver dynamically via the Context.registerReceiver() method.
Receive Broadcasts
To be able to receive a broadcast, application have to extends the BroadcastReceiver abstract class and override its onReceive() method.
If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system.
Problem with global broadcast
It is good practice to use broadcast receivers when you want to send or receive data between different applications. But if the communication is limited to your application then it is not good to use the global broadcast.
In this case Android provides local broadcasts with the LocalBroadcastManager class. Using global broadcast, any other application can also send and receives broadcast messages to and from our application. This can be a serious security thread for our application. Also global broadcast is sent system-wide, so it is not performance efficient.
What is LocalBroadcastManager?
For obvious reasons, global broadcasts must never contain sensitive information. You can, however, broadcast such information locally using the LocalBroadcastManager class, which is a part of the Android Support Library.
The LocalBroadcastManager is much more efficient as it doesn’t need inter-process communication.
Below are some of its benefits:
- Broadcast data won’t leave your app, so don’t need to worry about leaking private data.
- It is not possible for other applications to send these broadcasts to your app, so you don’t need to worry about having security holes they can exploit.
- It is more efficient than sending a global broadcast through the system.
- No overhead of system-wide broadcast.
Implementation
There is no additional support library dependency required in the latest version of Android Studio. However, if you want to implement local broadcasts in an old project, following dependency needs to be add in the app module’s build.gradle file:
Create a new instance of the LocalBroadcastManager
You can now send local broadcasts using the sendBroadcast() method like
Now create a broadcast receiver that can respond to the local-broadcast action:
Dynamically registered receivers must be unregistered when they are no longer necessary like:
You can find the reference code to implement Local Broadcast receiver from GitHub. In the sample code I have created an IntentService, which broadcasts current date and it is received by an Activity of the same application.
How to secure broadcasts
Restrict your app to receive broadcast
- Specify a permission parameter when registering a broadcast receiver then only broadcasters who have requested the permission can send an Intent to the receiver.
For example, receiving app has a declared SEND_SMS permission in the receiver as shown below:
- Set the android:exported attribute to “false” in the manifest. This restrict to receive broadcasts from sources outside of the app.
- Limit yourself to only local broadcasts with LocalBroadcastManager.
Control receiver of your broadcast
- You can specify a permission when sending a broadcast then only receivers who have requested that permission can receive the broadcast. For example, the following code sends a broadcast:
- In Android 4.0 and higher, you can specify a package with setPackage(String) when sending a broadcast. The system restricts the broadcast to the set of apps that match the package.
- Send local broadcasts with LocalBroadcastManager.
Conclusion
Hope you understand about the global and local broadcasts and their security consideration. To improve the performance of system Android O has changed the registration of broadcast receiver. From Android O you cannot register implicit broadcasts in your application manifest (few exceptions is there) but application can continue to register for explicit broadcasts in their manifests or at run-time. Read more on broadcast receiver at Android official document.
Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful. Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+ LinkedIn
Check out my blogger page for more interesting topics on Software development.
Источник
How to check if Receiver is registered in Android?
Posted by: admin November 12, 2017 Leave a comment
I need to check if my registered receiver is still registered if not how do i check it any methods?
I am not sure the API provides directly an API, if you consider this thread:
I was wondering the same thing.
In my case I have a BroadcastReceiver implementation that calls
Context#unregisterReceiver(BroadcastReceiver) passing itself as the arg after handling the Intent that it receives.
There is a small chance that the receiver’s onReceive(Context, Intent) method is called
more than once, since it is registered with multiple IntentFilters , creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver) .
In my case I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver) , but it would be
much cleaner if the API provided a check method.
There is no API function to check if a receiver is registered. The workaround is to put your code in a try <. >catch(IllegalArgumentException e) <. >block.
I am using this solution
You have several options
You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.
Create a class that extends the Receiver and there you can use:
Singleton pattern for only have one instance of this class in your project.
Implement the methods for know if the Receiver is register.
simplest solution
in receiver:
in code:
edit I
This really isn’t that elegant because you have to remember to set the
isRegistered flag after you register. – Stealth Rabbi
— “more ellegant way” added method in receiver to register and set flag
If you put this on onDestroy or onStop method. I think that when the activity has been created again the MessageReciver wasn’t being created.
You can do it easy….
1) create a boolean variable …
2) When you register your Broadcast Receiver, set it to TRUE
3) In the onPause() do it…
Just it, and now, you will not receive more exception error message on onPause().
Tip1: Always use the unregisterReceiver() in onPause() not in onDestroy()
Tip2: Dont forget to set the bolBroadcastRegistred variable to FALSE when run the unregisterReceive()
You have to use try/catch:
I used Intent to let Broadcast Receiver know about Handler instance of main Activity thread and used Message to pass a message to Main activity
I have used such mechanism to check if Broadcast Receiver is already registered or not. Sometimes it is needed when you register your Broadcast Receiver dynamically and do not want to make it twice or you present to the user if Broadcast Receiver is running.
Personally I use the method of calling unregisterReceiver and swallowing the exception if it’s thrown. I agree this is ugly but the best method currently provided.
I’ve raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added:
https://code.google.com/p/android/issues/detail?id=73718
Here’s what I did to check if the Broadcaster is already registered, even if you close you application (finish())
Firstime running your application, send a broadcast first it will return true/false depends on if your broadcaster in still running or not.
This is how I have done it, it is a modified version of the answer given by ceph3us and edited by slinden77 (among other things I have removed return values of methods which I did not need):
Then on an Activity class:
i put this code in my parent activity
List registeredReceivers = new ArrayList<>();
Just check NullPointerException. If receiver does not exist, then…
Related Posts
android – How do I display a CalendarView in an AlertDialog?
Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file:
How do I convert a PSD design to Android xml?
Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over.
Источник