Is using registerReceiver on the application class cosidered a good, known practice? - broadcastreceiver

Background
On Android, there are 2 possible ways to listen to system events via BroadcastReceivers :
statically, via the manifest
programmatically, via the code.
Since some projects contain a lot of activities, services, and "manager"-classes , it could be useful to have a single BroadcastReceiver that will notify all of its listeners on the app about what has happened, instead of having multiple BroadcastReceivers being used (and their code handling).
An example of such a BroadcastReceiver, is the one that listens to the connectivity changes:
#Override
public void onCreate() {
super.onCreate();
...
registerReceiver(new ConnectivityChangedBroadcastReceiver(), new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
...
}
The question
The purpose is to listen to the events while the app is "alive" (by services and/or activities) .
Using the manifest would miss this purpose, as it will wake the app each time the event occurs, even if the app doesn't need it.
Thing is, unregistering doesn't occur, and maybe it causes the OS treat the app in a different way because of it.
Does having a call to "registerReceiver" on the class that extends from Application is a good known practice?
Does it have any side effects and things to know about when using it?
Is there any alternative to this?
I just want to be sure it's considered safe to use.

we can't really know what is good or better for you.
I advise you to learn more about the difference between the registration ways of the receiver:
1/ in the manifest :
the handler of the receiver will be triggered each time that the correspondent event comes. Example: the messenger of facebook is lunched every time that you have internet connection to show you your notifications... or other applications are lunched when you connect to propose updates ...
in other words, the receiver is always registered.
2/ in a service or an activity or an application :
the receiver will be unregistered when the context of where it is registered is killed.
in other words, it depends totally of the context where it is registred , and you are obliged to unregister it somewhere in the code. exemple : one activity is waiting that a service ( which is doing something in the background) sends an alert to update something , then you can register the receiver in your onResume() and unregester it in your onPause().
Conclusion : It depends only in the life-cycle requirement of the receiver.
see also Broadcast Receiver Register in Manifest vs. Activity
Main difference between Manifest and Programmatic registering of BroadcastReceiver

Related

Can i register/unregister broadcast receiver in onCreateView/onDestroyView respectively?

I am broadcasting data (file download complete) from AsyncTask to Fragment and updating ListView accordingly.
I have read that broadcast receiver should be registered/unregistered in onStart()/onStop() respectively.
But in this case i will miss data which has been broadcasted when app is not foreground but running in background (onStop() called but onDestroyView() not called) .
So to resolve this issue can I register/unregister broadcast receiver in onCreateView()/onDestroyView() respectively?
Also suggest if there is any alternative solution to this.
Many thanks in advance.
I beleive it is common practice that broadcast receivers be registered in any method including onCreate() and be unregistered in any method including onDestroy(). Used in the onCreate() and onDestroy() methods are really common practice. I also know of maybe the only other way to register a broadcast receiver and that is to register it in the Manifest. That basically means that as soon as the app is run for the first time the broadcastReceiver will always be running in the baground. Hope this helps you.

Android Async Task does not update UI when application is in background

The application I am working on downloads and parses a large xml file to populate UI elements, namely search and a spinner. This is done through an async task. If the user decides to switch out of the application during this, the information is downloaded correctly, but then when the application is resumed, the UI will not be updated.
Is this because the changes can't be made while the application is not active? What is the best way to go about checking whether the UI was not updated on resume? Or instead should I be doing something with the Async task, checking whether the UI thread is available? I'm having a hard time debugging this because it involves leaving the application which ends the debugger.
You can achieve this scenario through the broadcast receive.
Follow the step:
Solution 1:
Step 1;
Register the broadcast receiver before executing the Asyntask.
Step 2:
send Broadcast in onPostExecute method of Asyntask.
step 3:
And then you can able receive your broadcast message in your activity.
and do whatever you want.
Solution 2:
Otherwise you can use Interface Call back for this Scenario.
Hope It will help you.
It should'nt. App being in background means View objects may or may not be there. Actually the entire process may be stopped or just deleted by android.
Use a Service to truly do processing in background. When processing is complete but UI is not there, post a notification to let user know, OR, save the results and provide it to UI the next time it binds to your service and ask for same thing (a.k.a caching).
The application in background may not be live. The O.S may destroy it in case of memory constrains.
The trick is to try an alternate logic.
When the application moves from background to foreground onresume() is called ,you could try saving the data to db and update the content on the resume call.
FYI.onPause() and OnResume() is called when the application goes background and foreground respectively.

Best method to run a periodic background service in java blackberry

Objective: I want to develop an UI application that runs a service/ task/method
periodically to update database. This service should start after
periodically even if my application is not active/visible/user exits
app. Similar to an Android Service .
I'm using BlackBerry Java 7.1 SDK eclipse plugin .
The options I came across are the following:
1) How to run BlackBerry application in Background
This link suggests that I extend Application instead of UIApplication. But I can't do that as my application has a user interface.
2) Make application go in background
I don't want my UI application to go in background, instead i just want my application to call the service periodically .
3) Run background task from MainScreen in BlackBerry?
This link suggests to run I a thread, but I don't think that if user exits my application then the thread will run in background
4) Blackberry Install background service from UI application?
This suggests using CodeModuleManager ,whose usage I'm unable to figure .
Please suggest what is the best way to achieve this objective or suggests any other better method .
I am new to blackberry so please pardon my ignorance.
To expand on Peter's Answer:
You will need to create two classes :
class BgApp extends Applicaton
class UiApp extends UiApplication
I guess you have already created the class that extends UiApplicaiton. So add another class that extends Application.
Then create a class that extends TimerTask and implement its run method to call the method that updates the database.
class UpdateDatabaseTask extends TimerTask
In the BgApp constructor, create a Timer. And schedule the UpdateDatabaseTask using the schedule(TimerTask, long, long) method.
Define alternate entry points, check the "Do not show on homescreen" and "auto run on startup" checkboxes for the bgapp's entry point.
It is easiest and simplest to use the builtin persistence mechanism (PersistentStore and Persistable interface) for storing data. Even if you use any other means like RecordStore or SQLDb, both UiApp and BgApp can use access the same database. The values updated by the bgapp will be accessible by the uiapp and vice-versa, automatically.
If you want to send a signal from bgapp to uiapp (for example when bgapp downloads new data you want the uiapp to reload the data instantaneously), post a Global Event (ApplicationManager.postGlobalEvent()) when the download is complete and listen for it in the screen that is displaying the data (GlobalEventListener interface).
There are code samples for each of these available as part of the SDK or search on the internet and you'll find a lot of implementations.
Good research, lots of interesting thoughts.
I think the best thing to do is to try the simple standard approaches and only make something more sophisticated if you need to.
Here are two options that would be regarded as 'standard', with brief advantages and disadvantages:
a) Make your UiApplication go to the Background
Instead of exiting when the user presses the 'close' button, your UiApplication will "requestBackground()". it will automatically be bought to the foreground when the user clicks on the icon, or selects your application from the task switcher. Then you can run a Thread whenever you want or in fact leave one running to update the database.
This is my preferred method. But you have to careful with memory management to make sure there are no leaks. And some people don't like the idea that the Application is visible on the Task Switcher all the time.
b) Alternate Entry
With this option, your one Application package contains two Applications, or more accurately, one Application and one UiApplication. The UiApplication is run when the user clicks on the icon. The Application runs as a background task, and updates the database for your UiApplication.
This looks like a more elegant solution, but introduces some possible communication issues, and is more difficult to debug.
In your case, since you are relatively new to BB, I would suggest that you use option a, and if you find it doesn't work for you, you will not find it that difficult to swap to option b.
And to comment on the Options you have already presented:
Sort of covered with option b
Option a
You are correct - if an Application exits, all the Threads are killed
Leaves the problem of creating the application in the first place and then debugging it. This is not really a solution for you, more an implementation method.
The above is brief, please ask if it is not clear.
This might help with b:
http://supportforums.blackberry.com/t5/Java-Development/Set-up-an-alternate-entry-point-for-an-application/ta-p/444847
Edit:
Editing this to respond to the questions and to expand on the alternative answer, which expanded on this one (bit circular I know...).
To answer the second question first, I agree with the other answer which states the alternate entry (background) and the foreground app can share an SQLite database.
With respect to how these two communicate, while they work just fine, personally I am not a great fan of Global Events because they are propagated to all Applications on the BlackBerry. You can achieve similar things in many alternative ways - the trick is to find something that is common to both applications so that they can communicate. To this end, I recommend using RuntimeStore. See this KB article:
http://supportforums.blackberry.com/t5/Java-Development/Create-a-singleton-using-the-RuntimeStore/ta-p/442854
Regarding how you persist your database, I like PersistentStore because it is present on all devices. But if you really have a database, and not persistent Objects, then SQLite seems the ideal thing to use. Personally I would not use RecordStore, but here is a discussion of the options:
http://supportforums.blackberry.com/t5/Java-Development/Introduction-to-Persistence-Models-on-BlackBerry/ta-p/446810
And just a clarification - in the example given, you have two applications, BgApp and UiApp. You will only have one main() method. This main method will use the args that you specify to determine which one to start, which it will create and have it "enter the dispatcher". If I could make a recommendation - use "gui" as the argument to specify that you will start your UiApplication. I have experienced a circumstance that the OS attempted to start my alternate entry Ui application with this String, regardless of what I had actually specified. Might have been a one off, but I have stuck to doing that ever since.
Finally two comments on the use of Timers and Timertask to provide triggered events. The first comment to make is whatever you run in the TimerTask should not take that long - so you should just use the TimerTask to initiate the download Thread (which might take a long time). Secondly for me, in this situation, I would not use Timer/TimerTask. I would rather just have a single Thread, which 'waits', and then processes. The advantage to me is that this can be adaptive. For example, if you fail to connect, then you might shorten the time till the next connection attempt. Or if it is after hours, then you might lengthen the time between connections to reduce battery usage. Or you might stop connecting completely when the battery is very low.
Hope this helps.

Is there a sendToActivity() method?

I have a program with about 8 Activity classes, and 1 Application class. I want my Application class to be able to communicate with every Activity, but on its own terms. I don't want the activity to ask the Application for data, I want the Application to send the Activity data. The problem with this, is that depending on the current state of the program I'm unsure what Activity will be open.
Is there a method of some sort which will send information from the Application to the CURRENT activity?
The Application class connects with an embedded Bluetooth Device and needs to receive different pieces of data depending on which Activity the user is currently in. I originally had it as a regular class, which was initialized in the MainMenu of my program and passed a Handler. However, it seemed like weak design to pass that Handler from Activity to Activity time and time again.
You could use a Callback Method
Every Activity has it's own callback method and registers that method onResume() in the Application Class. (it's like an onApplicationWantsToDoSomethingWithMeListener() ;)
or why not a Service in background? instead of the Application, since what you want sounds like a Service. More details?
EDIT:
I made a similar application with bluetooth, you should definetly use a Service for that, but you can communicate with your service per Application. Say the Service calls the callback in the Application look here for an implementation uf such a thing

Activity not responding error on emulator when using webservices in json parsing?

Am new to android, am developing application with websevices using json parsing with httpget method,cant use http post method in android actually.
It working fine normally, but many time it shows the error on emulator like activity not responding force close activity.when i put that url in browser it shows the result .but i don't know why this activity not responding error came.
I think the httprequest took more time to retrieve the data from server,but am not sure. any one help me to how to avoid this error or how to minimize this .
I want know what are the possibilities to get this activity not responding error.
Thanks,
Lakshmanan
You need to perform blocking operations such as I/O in a separate thread - see the below linked resource:
http://developer.android.com/guide/practices/design/responsiveness.html:
In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a dialog to the user, called the Application Not Responding (ANR) dialog, shown at right in Figure 1. The user can choose to let the application continue, but the user won't appreciate having to act on this dialog every time he or she uses your application. It's critical to design responsiveness into your application, so that the system never has cause to display an ANR dialog to the user.
To avoid ANR (Application Not Responding) dialog,
Your business logic code is inside doBackground() of AsyncTask and You may also need to override onPostExecute(),etc. After that it is better to invoke the async task in a Service (bound or normal service).
Service:
(bound service or normal service based on your requirement)
From, android office documentation:
A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.