I have created a Activity with few toggle buttons and based on the selection would like to perform specific operations at specific intervals. I have created the broadcast receiver and doing these activities in the onReceive(). I am using the alarm manager to run these tasks at particular intervals. If I don't un-register the recever in onDestroy I get an error saying there is leak, if I unregister the receiver in onDestroy it works fine but the receiver stops working.
I would like to keep the register listening even after the activity is closed, so that I keep performing particular tasks and specified interval. Please suggest
what you are looking for is a sticky broadcastreceiver. the best example i found so far is visible here --> http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html#broadcastreceiver_sticky
A normal broadcast intent is not available anymore after is was send
and processed by the system. If you use the
sendStickyBroadcast(Intent) method, the corresponding intent is
sticky, meaning the intent you are sending stays around after the
broadcast is complete.
Related
I'm trying to implement an app that times how long my phone screen is on throughout the day using a broadcast receiver.
I'm declaring Action_Screen_Off/Action_Screen_On in my broadcast receiver since I can't declare it in my manifest, and I've been debating on the best way to handle storing the amount of time that my screen was on.
Since I can't declare it in the manifest, Should I declare the broadcast receiver inside of the onCreate in my activity? My worry with that is, if my understanding is correct, is that my receiver would then be tied to the lifecycle of the activity and I would only be able to store the on/off times whenever the activity is active.
The whole point of the app is that it's working in the background, and then displaying graphs of usage once an activity is in the foreground.
This led me to think that a Service might be the best bet the handle the Broadcast receiver, but Google seems to now be recommending that we don't use background services, only bounded and foreground services.
How can I make sure that my app is receiving the on/off intents, without the activity that declares the receiver being in the foreground, and the receiver not depending on the lifecycle of that activity?
You need a background Service for this functionality. Your Service doesn't need to actually do anything, but it needs to be active all the time so that you have something to anchor your BroadcastReceiver to. In onCreate() of your Service, create an instance of the BroadcastReceiver and register for the screen on/off events. Make sure that you return START_STICKY from your onStartCommand() in your Service. This will ensure that the Service is always active, and Android will restart the Service if it kills off your process (for whatever reason). The BroadcastReceiver can just write the timestamps of the on/off events to a file, SQLite database or SharedPreferences and your Activity can then read this data and show the graphs or whatever.
after an extensive search I still can't find a solution to my problem:
I need a Broadcast that runs once a day, no matter if the App is running or not. However, IF the App is running, I also need to update the UI at the end of/after the Broadcast.
I can't use a programmatically registered Broadcast because it ends with the Apps lifecycle. But from a static manifest-registered Broadcast I can't access the UI (at-least I don't know HOW).
One option would be to have 2 different Broadcasts and cancel/start them in onPause and onResume, but I wonder if there is an easier solution?
The thing you need is not broadcast receiver along with AlarmManager or JobScheduler for api above 21 and greenrobot event bus.
AlarmManager Schedules the broadcast call once a day or at any time you want and every time if the broadcast is called you can trigger event from eventbus and receive that event in the place where you want it. The thing why to use event bus is we do not need to handle if the view is visible or not.iF the view is in re use state it triggers the event the view and one method is called by event bus and in that method you can do anything you want to do with view.
personally i don't prefer service because service execution is really expensive now a days.
Note: the package name where you put alarm manager and broadcast
receiver should be "alert" some samsung mobile are very optimized so
they will only let the package name with "alert to run fully". You
will also need on boot receiver to register receiver and schedule
alarmmanager in case if the phone is booted.
I am trying to create my first Android app. I would like a main-thread Activity (in my case: an ActionBarActivity) to receive notification of an event from a background Activity (in my case: an IntentService). I've read that using broadcasts should be the best way to do this.
To register a Broadcast Receiver for listening to broadcasts sent from the background activity, I am using the following code inside the main-thread activity:
// Register broadcast receiver
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.me.myBroadcast");
bManager.registerReceiver(bReceiver, intentFilter);
I tried putting this in the onCreate() method of my main-thread activity, but I quickly discovered that every time I restart the activity (e.g. closing the app and re-opening it), it seems to create "duplicate" broadcast receivers, which then trigger the Broadcast Receiver's onReceive() method multiple times whenever a single broadcast is sent. This is causing problems.
So I created a SharedPreferences file to save a boolean which remembers whether or not I have already created a Broadcast Receiver, so as to avoid creating duplicates. This works exactly as hoped, until I restart the device of course, after which the Broadcast Receiver is destroyed, and the app doesn't create a new one because the SharedPreferences boolean says it already has one.
I'm guessing I could patch this issue by setting up a new broadcast receiver to listen for a device reboot, which resets the SharedPreferences boolean, but I have this nagging feeling that I am overcomplicating things massively. What am I missing? Thanks for any help offered!!
To answer your question, you can ignore sharedprefs and register the broadcast receiver in onResume and unregister the receiver in onPause. This method is well described in Reporting Work Status(1) android doc. Note that, this way, you will get status updates only if Activity is in foreground. Use appropriate life cycle methods depending on your needs.
To report status back to foreground activity from service, my preference would have been ResultReceiver(2) class which feels natural compared to a broadcast. Also, if you need to report multiple status messages back, it will be clearer with statusCode param in onReceiveResult method of ResultReceiver class.
I have a feeling i already know the answer to this but im not sure. Im using a broadcast receiver to intercept incoming SMS messages.
I register the receiver the typical way using the registerReceiver function and when you unregister the receiver you use the function unregisterReceiver function. I keep a global broadcast variable to load and unload the receiver as needed.
If the app closes, like the user actually closes the application and i don't unregister the receiver in the onDestroy method which i know is bad practice, would there be a way to unregister the receiver the next time the app loads? Could i create another instance of that broadcast receiver and then unregister it?
If the app closes
You can say that your UI is in the foreground or not. And you can say that your app's process is in the foreground, the background, or terminated.
It is unclear what "closing" would equate to.
like the user actually closes the application
A user can move an app's UI and process to the background (e.g., press HOME). A user can destroy an app's UI and move its process to the background (e.g., press BACK from the last running activity). A user can terminate an app's background process (e.g., swipe the app off of the recent-tasks list). A user can force-stop an app (e.g., pressing the Force Stop button for the app in Settings).
It is unclear what "the user actually closes the application" equates to.
would there be a way to unregister the receiver the next time the app loads?
Either you have a reference to your BroadcastReceiver object, or you do not. If you do, call unregisterReceiver() on some Context, passing in that BroadcastReceiver instance. If you do not have the BroadcastReceiver instance, you cannot unregister the receiver. If your process had been terminated between when you registered the receiver and now, that receiver is gone and is effectively unregistered.
I'm reading the documentation now, and I have 1 thing to be fixed - please, tell me, what is difference between broadcast receiver and activity (without the fact that activity can show UI)? Broadcast receiver gets announcements using intent-filter, but Activity can do it too! Please, make me clear. Thank you.
Activity is something which work on your input or require an user intruption for launching any task but with the help of broadcast reciever you can listen the system services as once a broadcast receiver is started for listening incoming calls then each time when a incoming call it will launch your method what you have written for that for more explanation check these
http://developer.android.com/reference/android/content/BroadcastReceiver.html
http://www.vogella.de/articles/AndroidServices/article.html
You basically have it. An Activity is intended to be associated with a UI. By contrast a Broadcast receiver only 'catches' intents broadcast through the app / system. However, there are also implications for how the object is loaded into the system, and how long it sticks around. From the BroadcastReciever documentation:
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.
This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.
Keeping these differences in mind, the system may be able to more efficiently execute pieces of your app...
Activity is only active when you open it. When it is moved to the background, it is either paused or shut down.
A listener is always active on the background. The only thing that can "activate" a listener, is the thing it is listening for. Ex.: a broadcastlistener will detect (and react) when you receive a phonecall/sms, but will ignore the fact that you set your alarm (since it only pays attention to incoming/outgoing broadcasts)
the intent filter does pretty much the same thing for both, the difference is just how it is called. With activities, it requires the user to do something; with listeners, it requires the listener to be triggered.