Dynamic Broadcast receiver for Android widget - android

The Android widget documentation (http://developer.android.com/guide/topics/appwidgets/index.html#AppWidgetProvider) seems to indicate that you can set your own broadcast receiver to handle widget activity instead of using the AppWidgetProvider helper class. For reasons of activity/service structure this would be the most convenient way for me to manage the widget I would like to create.
Is it possible to do this with a broadcast receiver registered in OnCreate as opposed to on in it's own class. The trouble, I think, is that it then isn't registered in the manifest, and thus the widget never shows up in the list.
Documentation/examples of this setup are essentially non-existent. Does anyone know if this is possible or have a good example?

Is it possible to do this with a broadcast receiver registered in OnCreate as opposed to on in it's own class.
Not really. In theory, you could have two receivers registered, one in the manifest and one via registerReceiver(). I cannot imagine a scenario in which this would be a good idea, as your activity will not be running all of the time anyway, and so you need the manifest-registered receiver to do everything anyhow.

Related

How to make android start my application automatically when battery is fully charged?

My question is similar to this one:
battery receiver fully charged doesnt work
. That question has no answers.
Here are the approaches I have thought of so far:
Approach 1: Register a BroadcastReceiver in the AndroidManifest.xml for ACTION_BATTERY_CHANGED.
This won't work because of the following reason:
I cannot register a BroadcastReceiver in the AndroidManifest.xml to listen for ACTION_BATTERY_CHANGED because it is a Sticky Intent as stated here: https://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED.
Approach 2: Register a BroadcastReceiver programatically in the MainActivity.java's onCreate() method.
Issue with this approach is : Avoid registering duplicate broadcast receivers in Android
In addition to the above issue, I do not understand the scope of broadcast receivers properly. To be more precise, I don't understand what happens to the broadcast receivers that an app has registered when the app is:
1) Destroyed by the Android system by calling it's onDestroy() method
2) When the app is force stopped by the user via the Application Manager setting.
Could someone please explain it please?
Approach 3: Use a work around that uses SharedPreferences and a BroadcastReceiver for listening to device reboot.
Have a shared preference that let's me know if I have previously registered a broadcast receiver for ACTION_BATTERY_CHANGED. If yes, don't create a new one, else, create a new broadcast receiver for ACTION_BATTERY_CHANGED. As pointed out in the link in Approach 2, the value in the SharedPreference becomes invalid upon device reboot, so have a separate broadcast receiver to create the receiver again on reboot and update the shared preferences to reflect the same.
Although, approach 3 may work, I feel it is a cumbersome way. Is there a simpler approach?
Additionally, my application will be inefficient since it is going to run for every change in battery state. Is there a way to make it run, only when the battery is full, which is my main purpose?

Why is registering IabBroadcastReceiver in Activity a bad idea?

In Google's in-app billing Trivial Drive sample, a BroadcastReceiver is registered to listen for messages about updated purchases, after the IabHelper setup has successfully completed.
The author however has included the following note:
Note: registering this listener in an Activity is a bad idea, but is done here
because this is a SAMPLE.
Why is this a bad idea for this listener?
This comment can be found in the OnIabSetupFinishedListener definition in the onCreate method of MainActivity in the source code for the Trivial Drive sample
My guess is that the BroadcastReceiver may get destroyed if it's in an Activity. BroadcastReceivers are usually declared in the manifest and are not manually instantiated by the developer, but by the OS. If it is registered in code, the only reference the Android OS has to the BroadcastReceiver is that particular instance which is tied to the lifecycle of the Activity it's contained in. If that Activity were to die/finish/stopped to save memory, then the BroadcastReceiver declared inside would most likely stop receiving updates.
As we know the broadcast receiver should not bounded with activity it should separate from activity lifecycle. Usually the broadcast receiver should define inside the androidmanifest file. Doing this allow activity can easy listen the update when it clearly visible to the user and avoid listen in case activity no long visible to the user by un register inside onStop/onDestroy.
The best way to implement it using Eventbus + Broadcast receiver class. Define the receiver into the android manifest. when the update come it will inform to the receiver class. We fire the event that will send to each activity that register event would receive this message. This way inside your application where you need the update you can easily subscribe and listen the event.
Thanks
Because if we register a BroadcastReceiver in Activity, then it's lifecycle is bind to the Activity's lifecycle. So when the Activity is destory, the Receiver will not worked. Therefore it can not receive any boardcasts while the Activity is not running.
May be you will lose the boardcast which of user's purchase.
In this sample, we always call mHelper.queryInventoryAsync(mGotInventoryListener);
in the Activity's OnCreate() function. So we don't worry about that as the author comment in the code.

Could I use just one BroadcastReceiver in my android app?

I am kind of confused about the BroadcastReceiver.
As title, I don't think I need another one BroadcastReceiver in my app.
Or, is there something wrong if I use a bunch of BroadcastReceiver in my app?
I think it will affect my OS execute memory and performance, am I right.
Thank you for your time and hot-heart.
Its all up to you. You can have multiple BroadcastReceiver for different sets of intent-filter or use single broadcast receiver to handle all the intent-filters.
Usually its better to define different receivers based on the set of intent-filters which are supposed to offer functionality for a related group of task.
Like I said, its all up to you. If you have a large set of intent-filters and you want your code to be handled properly (based on the similar classification of tasks it performs) then go for multiple receivers. Otherwise its easy and logical to handle few filters in single receiver.
Moreover, the performance of your app will not be obstructed as it depends on the execution of tasks with in the receiver, not the quantity of receivers or filters.
Tip: Try to introduce Threads wherever you are expected to perform some heavy lifting :)
It's considered that class should have one responsibility. So, if your BroadcastReceiver handles both SMS and CALL intents, then consider having multiple receivers.
You can declare as many BroadcastReceivers as you want on your app. It will affect if on every broadcast you receive you start doing a million long running background operations.
But does the app you're planning really need all those receivers?
There're some APIs to programmatically enable/disable your declared receivers, might be a good option too.
edit:
I guess it would be easier if you do a little test yourself.
On your Eclipse, create a new Android Project.
Create a class that extends the BroadcastReceiver.
Save and close it.
Now go to the manifest, Application tab, Application Nodes, ADD button, Add a receiver.
Wait for the Eclipse to search your application and find the one you just created.
Inside the receiver put a new Intent Filter. Don't need name or anything.
Inside the filter put an Action.
In the action name, check the drop-down menu.
Those are ALL the different actions a BroadcastReceiver might be receiving. So it just make it simpler and more organized for some application to implements more than one receiver, one receiver for each different type of action. Or maybe it's only receiving two very similar actions and it's simpler to make it all in one receiver.
Does it make sense?

What does/does not belongs in WidgetProvider

Widget Provider is a specialized BroadcastReceiver.
Assuming there exists an Application, 1-n android service,1-k activities, and potentially additional 0-n broadcast receivers that are not widgets, I would like to verify what belongs and does not belong logically inside the broadcast receiver. Here are some items ..
And assuming that generally what gets launched is the widget first.
Please comment on any of the items as to whether they belong inside or outside the widget and why. Thanks.
1) If the application needs to always listen for certain events whether they show up in the widget or not where should this go? In the Widget? If not what would keep the broadcast receiver available to listen to the events for the application?
2) Should the widget issue notification? or request a service to issue them? ie should the notification logic reside in the widget itself or in the service.
3) Should the widget issue broadcasts or ask a service to do this?
4) Should the widget ever access any system services like like Notification Manager, PowerManager etc Why, Why not?
5) Should the widget keep any of its own state? If it should not keep state how can it change what it displays? Like a different text or icon?
6) Should the widget start off activities or let a service handle this?
7) is it ok to user the context passed to update and receiver or should one use ctx.getApplicationContext() to do things like context.startService? ( Perhaps the one passed in is the application context ? )
Quoting myself from your cross-post to the android-developers Google Group:
Your entire question is phrased around "the Widget". There is no "the
Widget". From the opening sentence of your question, I am interpreting
"the Widget" to mean "a subclass of AppWidgetProvider that handles the
processing for an app widget or family of app widget instances".
1) If the Application needs to always listen for certain events
whether they show up in the widget or not where should this go? In the
Widget?
There is no reason for an AppWidgetProvider to respond to other
broadcasts, since anything can update the app widget's RemoteViews.
And an AppWidgetProvider cannot register listeners (e.g.,
PhoneStateListener).
Hence, I would say the answer here is "no".
2) Should the widget issue notification? or request a service to issue
them? ie should the notification logic reside in the widget itself or
in the service.
Technically, AFAIK, raising a notification is cheap and therefore safe
for an AppWidgetProvider to do.
Logically, an AppWidgetProvider should never have any reason to raise
a notification, IMHO.
3) Should the widget issue broadcasts or ask a service to do this?
Technically, AFAIK, sending a broadcast is cheap and therefore safe
for an AppWidgetProvider to do.
Logically, an AppWidgetProvider should never have any reason to send
broadcasts, IMHO.
4) Should the widget ever access any system services like like
Notification Manager, PowerManager etc Why, Why not?
This cannot be answered in the abstract.
5) Should the widget keep any of its own state? If it should not keep
state how can it change what it displays? Like a different text or
icon?
It may need to. For example, suppose you have an app widget that shows
the weather for a certain city. The configuration activity for that
app widget allows the user to choose the city. Somewhere, you need to
store that city, and distinct from the cities that any other instance
of that app widget may need (e.g., user adds two copies of the app
widget to track weather in two cities).
6) Should the widget start off activities or let a service handle
this?
An AppWidgetProvider should never have a reason to directly "start off
activities", nor should a service triggered from an AppWidgetProvider
have any reason to directly "start off activities", IMHO.
However, either are perfectly welcome to create PendingIntents that
"start off activities" and attach them as click handlers for widgets
in an app widget's RemoteViews.
7) is it ok to user the context passed to update and receiver or
should one use ctx.getApplicationContext() to do things like
context.startService? ( Perhaps the one passed in is the application
context ? )
Most things you can just use the passed-in Context. One thing that
will not work for is using registerReceiver() with a null receiver to
get the last value of a sticky broadcast, such as
ACTION_BATTERY_CHANGED -- for that, you will need to use
getApplicationContext().

Android: onAppWidgetChanged doesn't appear to exist

This is the description of AppWidgetHost.startListening():
Start receiving onAppWidgetChanged
calls for your AppWidgets
I can't find any reference to this mysterious onAppWidgetChanged thing anywhere. The only Google hits are quotes from the same piece of documentation.
What is it actually referring to? What does one need to call, override, or implement to get widget updates?
Its very unlikely that you need to implement a Widget host yourself. The home page is an existing Widget Host. Most likely what you are looking to do is Implement a WidgetProvider which basically means extending android.appwidget.AppWidgetProvider and overriding two methods:
onUpdate() and onReceive() some time onEnabled too. You almost never need to implement a Widget host, but if this is your goal please clarify. The widget provider is essentially a broadcast receiver which is designed to run inside widget host (usually home). The widget provider might live for only milliseconds, to process the broadcasted events and processing one of them is mandatory and must be specified in the manifest. To communicate out information the widget provider like any broadcast receiver extends context and can issue startActivity(intent) or startService(intent) I think this is most likely what you need to do unless you really are implementing a Widget Host.

Categories

Resources