Connect BroadcastReceivers - android

I have a broadcast receiver class, which I want to connect to a broadcast receiver in the main activity class, in order to call a method which originally called the broadcast receiver CLASS.
I have been struggling to find out how this would be done, and I think I am over complicating things. I saw something about using registerReceiver in the main activity class, but I don't think this is what I want.
This is the code setup in case I confused you.
MainActivity.class
public class MainActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
restartAlarm();
}
}
private void restartAlarm(){
//Do some stuff and call the RecursionReceiver class
}
}
RecursionReceiver.class
public class RecursionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Somehow call the broadcast receiver in the main class
}
}
EDIT: I will provide some more details.
What I am trying to do is set an alarm that will trigger at a certain point, which will call the broadcast receiver class. This class should in turn call the reset alarm method, which will reset the alarm.
No, I can't use a repeating alarm for what I want. This is because I am setting another alarm that requires this alarm. The other alarm will be set to trigger at a certain time, plus or minus a random number of milliseconds. It should not trigger at the same interval. However, I need it to start after the same period of time. So if I have that alarm to trigger every day at 6pm and want a offset of + or - 60000 milliseconds (one minute), the alarm will trigger within the boundaries. I have accomplished this, but I need a way to reset the alarm at the desired time, not at the trigger time. Plus I need to redo calculations to change the offset time.
My solution to this is have a second alarm that does nothing but recall the method to start both alarms at the time when the offset alarm SHOULD reset. If there is an easier way to set the second utility alarm, then let me know. Otherwise, I am confused about how to recall the method in the activity class from a broadcast receiver class.
The solution I found said I needed to do it with registerReceiver and have a BroadcastReceiver in the activity class. Then I could activate the receiver from the one that the alarm calls, and call the method from the receiver in the same class as the method. But there was no explanation for the code and it has highly confused me.
I am confused on how to make the receiver work from inside the class. I have made external broadcastreceivers work, but not local ones.

Related

How to set alarm thrice in everyday in android?

I need to set Alarm on 9.00 AM, 11 AM and 1PM in everyday.
Simple solution is to use three different pending Intent but Is it any other way to implement same with one pending Intent?
Thanks in Advance!
Thanks, Got solution
Only need to change request code in same Intent. It will not cancel previous alarm. Click Here for solution
If you have a limited number of alarms that at any time need to be scheduled, maybe use one PendingIntent for each alarm can be fine.
However if you have a potentially unlimited (or maybe just a lot) number of alarms to be scheduled, I think that a better approch can be to provide a scheduler that can act over the scheduling information. For example, if you need to create something like a calendar where you can set one or more Event for each day, you should consider this approch.
You can take a look at the Alarm section of tha Android Calendar project
As you can see there is a class named AlarmScheduler in which you have a method
void scheduleNextAlarm(Context context, AlarmManagerInterface alarmManager,
int batchSize, long currentMillis)
That determines the next alarm that need to be scheduled.
In the specific implementation you can see that the method calls another method:
queryUpcomingEvents()
that operates over a content provider (Calendar provider) and gets the upcoming events.
Each time you trigger a new Alarm you can reschedule a new one, looking in the content provider (or wherever you store your scheduling information), or you can applay different scheduling policiy. For example if an user create a new remider for an Event on the calendar you need to reschedule the alarms (for example you could decide to schedule all the alarms for today, or just the next alarm).
In my applications I usually use the following code (inside the onReceive() of the BroadcastReceiver that is triggered when the alarm fires):
private void restartScheduler(Context context){
Intent t = new Intent("it.gvillani.socialapp.alerts.SCHEDULE_REQUEST");
context.sendBroadcast(t);
}
And then of course I have a BroadcastReceiver that waits for that action and try to reschedule the alarms:
public class SchedulerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals("it.gvillani.socialapp.alerts.SCHEDULE_REQUEST")) {
startScheduler(c);
}
}
private void startScheduler(Context c) {
AlarmScheduler.clearAlarms(c);
AlarmScheduler.scheduleNextAlarm(c);
}
}

android - update specific activity UI from onReceive

I have a BroadcastReceiver, and the onReceive is called from two different postExecute methods in two different asyncTasks, in two different Activities.
I have a third activity that is running all the time called HomeActivity, and I want to publish some text to the HomeActivity's UI from the onReceive method.
Is it possible? I know that the context parameter is the context of the activity who raised the onReceive, but I want to access the HomeActivity's UI.
Here is the code
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// here I want to publish some text to the HomeActivity
}
}
any ideas? thanks in advance
You want to change text in your running activity based on what you receive in the onReceive of the BroadcastReceiver? Right? One way is that you can use LocalBroadcast. See LocalBroadcast Manager.
For how to implement is, there is a great example on how to use LocalBroadcastManager?.
LocalBroadcast Manager is a helper to register for and send broadcasts of Intents to local objects within your process. The data you are broadcasting won't leave your app, so don't need to worry about leaking private data.`
Your HomeActivity can registers for this local broadcast. From the MyBroadcastReceiver you send a LocalBroadcast from within the onReceive (saying that hey, I received a message. Do you want to do something now activity). Then inside your Activity you can listen to the broadcast. This way if the activity is in the forefront/is active, it will receive the broadcast otherwise it won't. So, whenever you receive that local broadcast, you may change the text etc, if activity is open.

Android sendBroadcast - waiting for BroadcastReceiver to finish

I'm using a BroadcastReceiver in my Android app which simply contains the following piece of code:
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
GcmIntentService.isHandled = true;
Toast.makeText(context, "broadcast receiver test", Toast.LENGTH_SHORT).show();
}
}
I'm using this receiver to determine if my activity is running and carry out some updates in a ListView without having any notifications produced by GcmIntentService.
With the code being simple so far, only creating a toast message, I'm unable to catch the boolean value from GcmIntentService.isHandled as soon as the sendBroadcast is invoked.
Is it possible in any way to determine if the code for my receiver has finished running. I understand that sendBroadcast is an asynchronous call, and I'm making use of Thread.sleep(1000) so far to wait for the isHandled value, but it would be nice if there is a more reliable method on achieving this.
Any thoughts?
Your question can be divided to two parts:
1.How to know that if there is a receiver actually received the broadcast.
2.How should the receiver notify the service that message is been handled.
It seems difficult to achieve the first goal through standard Intent api, instead I suggest you may try the "observer pattern".
You may create a global Observable object in your Application and make your Activity implements Observer, register itself in onCreate() and unRegister in onDestory().Inside the Service you can check if there is an Activity running through countObservers() and then simply notify it.

BroadcastReceiver stops working

In general i have a service that sends an intent to my activity which is ALWAYS on every 6 sec and a BroadcastReceiver everytime on receive updates a timer.
I found by accident that after a while ( this is random ) that the particular receiver stops working.
OnPause i unregister it and onResume i register it again.
Also this happens randomly in any devices and android versions.
I found by researching on the web , that after onReceive the receiver is ready to killed by Android but mine keeps getting intents.
"Receiver Lifecycle
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.
"
FYI i have declare it like this inside my activity
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent intent) {
Log.i("Intent received", "+_ " + intent.getAction());
if (intent.getAction().equals(TEST)) {
//do sth
} else {
//do sth else
}
}
}
Thans a lot even for taking the time to read :).
I dont declare anythin to my manifest and as for my logcat i must be over my phone the moment it happens. The service is a simple send broadcast after one async task. The last test i made was ensuring that the code from the service was running by logging the beeing sent. And the service kept on.
I am away from my code write now but i think there will be no help because is very simple. Thnaks
Well i could still figure out but I find a solution to my problem
Timer now is in the activity and receiver is sending the event but after 10000 tries i want to trigger the END EVENT. Now the receiver since he didn't work i couldn't get it but now i Start an intent with extras for the same activity always with flags new_task and clear_top.
No matter if my receiver is working or not, since the service is ok i will start the specific Activity and pseudo-show the END EVENT.
PS:: This behavior isn't always trigger but sometimes. So now i am ok.
If i am not understood please comment and ask anything. Thanks

BroadcastReceiver receives when service is started each time

I have a dynamically registered BroadcastReceiver on a Service. It gets AudioManager.RINGER_MODE_CHANGED_ACTION as IntentFilter. Every time I start the service I get the log message in onReceive() method. It works normally after that. I do not want it to receive once when service is started each time. Could you please tell me what I am missing here?
receiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Log.d("zil", "degisti");
}
};
IntentFilter filter=new IntentFilter(
AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(receiver,filter);
The intent you are interested in, AudioManager.RINGER_MODE_CHANGED_ACTION, is "sticky". That means that the system always keeps the last broadcast sent and whenever a BroadcastReceiver is registered that is interested in that Intent, it receives it right away. This is a very useful feature but sometimes it isn't what you want ;-)
I assume that you are only interested in actual "change" events. In this case you need to ignore the "current" event and listen only for any events that happen in the future. Lucky for you, there is a solution:
In 'onReceive()' do the following:
if (isInitialStickyBroadcast()) {
// Ignore this one as we aren't interested in the current state
} else {
Log.d("zil", "degisti");
// Do whatever you want to do with the event here
}
unregisterReceiver(receiver);
this probably wont work because you created an Anonymous inner class implementation of BroadcastReciever. instead create a nested/private class that extends BroacastReceiver in the activity where you want your service started. Then dynamically register and unregister your receivers in the Activity lifecycle callbacks

Categories

Resources