Setting up of multiple alarms in android - android

i am having this code for setting multiple alarms for creating a reminder application .The code works fine when a single alarm is put. However when i set mutiple alarms I am getting only the first reminder and that too invoked when the alarm time of the last reminder is reached.
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class ReminderManager {
private Context mContext;
private AlarmManager mAlarmManager;
public ReminderManager(Context context) {
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}
public void setReminder(Long taskId, Calendar when) {
Intent i = new Intent(mContext, OnAlarmReceiver.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, (long)taskId);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
}
}
On alarm reciever i have
public class OnAlarmReceiver extends BroadcastReceiver {
private static final String TAG = ComponentInfo.class.getCanonicalName();
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received wake up from alarm manager.");
long rowid = intent.getExtras().getLong(RemindersDbAdapter.KEY_ROWID);
WakeReminderIntentService.acquireStaticLock(context);
Intent i = new Intent(context, ReminderService.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, rowid);
context.startService(i);
}
}

Your code shows that you have hard coded the 2nd parameter of
PendingIntent.getBroadcast(c, 0, i, etc
As far as I am aware, this parameter is the identifier for your alarm. Use a different value for each alarm if you want to set multiple alarms.
Try
PendingIntent.getBroadcast(c, taskid, i, etc
Alternatively, I handled this by only ever setting one alarm at a time (the earliest one).
When that alarm is triggered I then set the alarm for the next one.

Related

android Setting Multiple Alarms

First of all , i'd read many many answers about this problem ,
I want to set 5 alarms working but with different times , the problem is the last one overrides the others so i see the last one only ,
i tried to change the request code of the PendingIntent to make it unique but the problems still as it is :
i'd rewritten the code many times really but the same result,
i tried to make one method for all the alarms and changing the request code in but no use , also i tried to make different methods for every alarm with unique request codes but still the last alarm overrides the others,
here is my code for two methods as an example :
Note :
variables that i have
fajrMillis,dhuhrMillis : are the milliseconds which are converted to a calendar to set the time in
fajrMessage,dhuhrMessage : the string messages to be sent to the receiver class to the notification in it
Calling the two methods :
setFajrAlarm(fajrMillis, 1, fajrMessage);
setDhuhrAlarm(dhuhrMillis, 2, dhuhrMessage);
public void setFajrAlarm(long millis, int id, String message) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
PrayersReceiver.notificationId = id;// 1
PrayersReceiver.notificationMessage = message;// "حان الآن موعد صلاة الفجر"
Intent intent = new Intent(getBaseContext(), PrayersReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(),30000, pendingIntent);
}
public void setDhuhrAlarm(long millis, int id, String message) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
PrayersReceiver.notificationId = id;// 1
PrayersReceiver.notificationMessage = message;// "حان الآن موعد صلاة الظهر
Intent intent = new Intent(getBaseContext(), PrayersReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 2, intent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), 5000, pendingIntent);
}
//---------------------------------------------------------------------------------
The Receiver Class
package com.prayers;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class PrayersReceiver extends BroadcastReceiver {
public static String notificationMessage = "";
public static int notificationId ;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Time For Prayer", 3000).show();
// -----------------
// --------------Notification Part---------------------------
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("حان الآن موعد الصلاة")
.setContentText(notificationMessage);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notificationId, mBuilder.build());
}
}
Thanks in advance , hope to get the answers soon
I knew the answer so if anyone faces this problem to get the solution :
i was setting the variables values in the receiver class so the last method call overrides the previous calls :
PrayersReceiver.notificationId = id;
PrayersReceiver.notificationMessage = message;
the problem was in these two lines in the method body :
so it got solved by :
Intent intent = new Intent(getBaseContext(), PrayersReceiver.class);
intent.putExtra("notificationId", id);
intent.putExtra("notificationMessage", message);
and in the receiver class get the two values :
Bundle bundle = intent.getExtras();
if (bundle == null) {
Log.i("PrayersReceiver", "bundle is null");
return;
}
notificationId = bundle.getInt("notificationId");
notificationMessage = bundle.getString("notificationMessage");

Android AlarmManager after reboot

I have a set of alarms that I need to keep after reboot. I've tried using on an boot receiver but they won't start again. I'm not sure if I understand the boot receiver and how to then restart all the alarms. I already have one receiver for my notifications, but don't know whether I can use the same receiver or if I need a new one?
Could anyone point me to any good tutorials or help me out?
Cheers
Code :
DatabaseHandler db = new DatabaseHandler(this);
List<UAlarm> alarms = db.getAllAlarms();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
for (UAlarm ua : alarms) {
String programme = ua.getTitle();
String startTime = ua.getStart();
String endTime = ua.getEnd();
String nowPlaying = ua.getChannel();
db.addAlarm(new UAlarm(programme, startTime, endTime, nowPlaying, ""));
final UAlarm ut = new UAlarm();
ut.setTitle(programme);
ut.setStart(startTime);
ut.setEnd(endTime);
ut.setChannel(nowPlaying);
ut.setId(db.getLastEntered());
String [] bla = startTime.split(":");
int hour = Integer.parseInt(bla[0].trim());
int minute = Integer.parseInt(bla[1].trim());
minute -= 2;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
Intent intenta = new Intent(this, NotificationMenu.class);
String name = programme;
intenta.putExtra("name", name);
intenta.putExtra("id", db.getLastEntered());
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ua.getId(),
intenta, PendingIntent.FLAG_CANCEL_CURRENT);
am.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);
}
}
with NotificationMenu being the notifications, which is why I'm using the AlarmManager
I'm not sure if I understand the boot receiver and how to then restart all the alarms.
Just call your code to call setRepeating() (or whatever) on AlarmManager.
For example, in this sample project, PollReceiver is set to receive BOOT_COMPLETED. In onReceive(), it reschedules the alarms:
package com.commonsware.android.schedsvc;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class PollReceiver extends BroadcastReceiver {
private static final int PERIOD=5000;
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
static void scheduleAlarms(Context ctxt) {
AlarmManager mgr=
(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, ScheduledService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
}

How to start an activity using AlarmManager etc

I am trying to start code inside an activity at regular intervals using Alarm manager. I have looked at various examples on here but they have not really helped.
For testing purposes, all I am trying to do is pop up a toast at 10 second intervals, but nothing seems to be happening at all. Please help guys!
I have this in the manifest (also declarations for all three activities):
<receiver android:name=".receiver.AlarmReceiver"></receiver>
Code from main activity, in OnCreate:
//
// Setting up the Alarm Manager
//
Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long timerInterval = 10 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent);
//finish();
AlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show();
Intent scheduledIntent = new Intent(context, MyService.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
MyService.java:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Toast.makeText(getBaseContext(),"test message.",
Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Your activity is not showing, because you are calling startActivity() on an Intent that identifies a Service. You should see warnings related to this in LogCat.
I humbly suggest that you use LogCat yourself, via the Log class, for logging background operations, rather than attempting to use a Toast.
test this code:
private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}

Starting a service via Alarm does not work

I have the following broadcast reciever that gets called when the phone boots up (Bootreciever.java) and I'm trying to start a service that runs intermittently using a repeating alarm.
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Inside onRecieve() :D" , Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), "Inside onRecieve() :D");
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyService.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 3000, 1000, pi);
}
Basically, I'm setting a repeating alarm to trigger 3 seconds and on every second after that. The bootup complete broadcast is received just fine - but the service does not start. MyService.java looks like this:
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello from MyService!", Toast.LENGTH_LONG);
Log.d(getClass().getName(), "Hello from MyService!");
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
What am I doing wrong when starting the service?
Logcat does not tell me anything and I have the service defined in my manifest. On its own this service works when called using startService() but seem to fail when used within a PendingIntent.
Instead of PendingIntent.getBroadcast() use PendingIntent.getService()
I think you should check your duration because android gets a bit picky with alarms that trigger too often. In order to start a service the best way is to set the alarm to broadcast the intent to a broacast receiver and then get it to start your services.
Example 1 the receiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class QoutesReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// log instruction
Log.d("SomeService", "Receiving Broadcast, starting service");
// start the qoute service
Intent newService = new Intent(context, SomeService.class);
context.startService(newService);
}
}
Example 2 the Function that sets the alarm (this example runs every 2 mins):
public void setAlarm(Context context) {
// Get the current time
Calendar currTime = Calendar.getInstance();
// Get the intent (start the receiver)
Intent startReceiver = new Intent(context, MyReceiver.class);
PendingIntent pendReceiver = PendingIntent.getBroadcast(context, 0,
startReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
// call the Alarm service
AlarmManager alarms = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
//Setup the alarm
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
currTime.getTimeInMillis() + (2 * 60 * 1000), 2 * 60 * 1000,
pendReceiver);
}

Android : how to set the calendar alert in android

Is it possible to show calendar alert in android, so that on the specified date the alert should pop up and remind the user regarding the task.
Sorry, there isn't currently a calendar API in the SDK. You can however implement your own alarm with the AlarmManager showing your own UI at the time you schedule with it.
first of all to set the alert in calendar application you have to make the permit-ion :
Now, that the alarm receiver is set, lets take a look at the class that will set and cancel the alarms:
package SomeApp.SomeApp;
import java.util.Calendar;
import java.lang.String;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;
import android.widget.Toast;
/**
* When this code is run only one alert will be displayed even though 2 alerts were
* were setup (as one of them will be cancelled later on
*/
public class SomeApp extends ListActivity {
/* for logging - see my tutorial on debuggin Android apps for more detail */
private static final String TAG = "SomeApp ";
protected Toast mToast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert_list);
try {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+15000, sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
}
You will notice that this is only a "one-shot" alarm. If you want to set a repeating alarm, it is explained in Android's documentation. However, I will write on that too if there is demand for it. Now, let's examine the code. For setting an alarm, you will need 4 things:
The class that's setting the alarm
The class that will be called when the alarm "goes off"
The time at which the alarm should go off
A requestCode (which will use as a unique ID to identify the alarms) used in PendingIntent.
For cancelling an alarm, you need 3 things:
The class that set the alarm
The class that was to be called when the alarm "goes off"
The requestCode you used for PendingIntent object.
We have covered 2 things - the declaration of the receiver in our manifest file and the class that sets and cancels alarms. Now, we need to look at the class that will be called when the alarm goes off.
package someApp.someApp;
import java.util.Calendar;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.util.Log;
import android.widget.Toast;
/** All receiver classes must extend BroadcastReceiver */
public class AReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context con, Intent in) {
try {
/* Display an alert */
Toast.makeText(con, "hello my jello ", Toast.LENGTH_LONG).show();
} catch (Exception r) {
Toast.makeText(con, "You were supposed to do something"
+" now but I can't retrieve what it was.",
Toast.LENGTH_SHORT).show();
Log.e("ALARM_RECEIVER", r.toString());
}
}
}
AND YOU are able to use this other ans also...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
setAlarm(cal);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 30);
setAlarm(cal);
//etc
}
public void setAlarm(Calendar cal) {
try {
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}

Categories

Resources