I'm getting this error in my Android broadcast receiver code below (the last line). I don't understand why this constant isn't available in this context?
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Code to be executed after a phone reboot
PendingIntent pi;
AlarmManager am;
// Read the pending_alarms table and re-create the pending intents
List<pending_alarm> pending_alarm = new TableControllerPendingAlarm(
context).read();
if (pending_alarm.size() > 0) {
int idx = 0;
for (pending_alarm obj : pending_alarm) {
long id = obj.id;
String mealItemDesc = obj.alarm_desc;
int alarmMinutes = obj.alarm_minutes;
int alarmHours = obj.alarm_hours;
long mealPlanId = obj.id;
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, obj.alarm_day);
cal.set(Calendar.MONTH, obj.alarm_month - 1);
cal.set(Calendar.YEAR, obj.alarm_year);
cal.set(Calendar.MINUTE, obj.alarm_minutes);
cal.set(Calendar.HOUR, obj.alarm_hours);
Intent alarmIntent1 = new Intent(context, AlarmReceiver.class);
alarmIntent1.putExtra("meal_item_desc", obj.alarm_desc);
alarmIntent1.putExtra("meal_id", obj.fk_meal_id);
alarmIntent1.putExtra("pending_alarm_id", obj.fk_meal_plan_id);
alarmIntent1.setAction(Long.toString(id));
idx++;
pi = PendingIntent.getBroadcast(context, idx, alarmIntent1, FLAG_UPDATE_CURRENT);
That flag is a constant which is not part the current class. It's part of the PendingIntent class.
So address it as such:
PendingIntent.FLAG_UPDATE_CURRENT
FLAG_UPDATE_CURRENT belongs to Intent.
Change
pi = PendingIntent.getBroadcast(context, idx, alarmIntent1, FLAG_UPDATE_CURRENT);
to
pi = PendingIntent.getBroadcast(context, idx, alarmIntent1, Intent.FLAG_UPDATE_CURRENT);
Related
Goal:
I want to have a service that write a record every 5 minutes in the table of database.
The work done:
To accomplish the goal, an Alarmmanager was used that did this every 5 minutes. Unfortunately, after a while the Alarmmanager goes off (for android 8 or above).
public class SensorInfoAlarmManager {
public void setReminder(Context context) {
MsdSQLiteOpenHelper msdOpenHelper = new MsdSQLiteOpenHelper(context);
SQLiteDatabase dbInstanse = MsdDatabaseManager.getInstance().openDatabase();
int interval = msdOpenHelper.getSensorInfoInterval(dbInstanse);
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
setcalendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE));
setcalendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND));
cancelReminder(context);
ComponentName receiver = new ComponentName(context, SensorInfoAlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, SensorInfoAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
android.app.AlarmManager am = (android.app.AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setRepeating(android.app.AlarmManager.RTC_WAKEUP, (long) interval* 1000, (long) interval * 1000, pendingIntent);
}
}
It seams android does not allow the Alarmmanager to always be running.
I used from these solutions 1, 2 and 3, but no result found.
What is the problem? Is there a better solution?
I need to make a notification where in the user will choose the date and time the notification will start. In order for that, I store the date, time and notes in the Database. Now I want to start the alarm using the data from the database and using the id of each alarm as a unique id for the PendingIntent.
This is the how I get the data from the database
db=new events_database(events_main.this);
c=db.queryData("select * from events_list ORDER BY event_ID ASC");
if(c != null && c.moveToNext())
{
int id=c.getInt(0);
String type=c.getString(1);
String date=c.getString(2);
String time=c.getString(3);
String note=c.getString(4);
String[] newDate=date.split("/");
int year=Integer.valueOf(newDate[0]);
int month=Integer.valueOf(newDate[1]);
int day=Integer.valueOf(newDate[2]);
String[] newTime=time.split(":");
int hour=Integer.valueOf(newTime[0]);
int min=Integer.valueOf(newTime[1]);
Alarms(id,year,month,day,hour,min,type,note);
}
After getting it I pass the data into the Alarms method
public void Alarms(int id, int year, int month, int day, int hour, int minute, String type, String note) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR,year);
calendar1.set(Calendar.MONTH,month);
calendar1.set(Calendar.DAY_OF_MONTH,day);
calendar1.set(Calendar.HOUR_OF_DAY, hour);
calendar1.set(Calendar.MINUTE, minute);
calendar1.set(Calendar.MILLISECOND, 0);
if (calendar1.before(Calendar.getInstance())) {
calendar1.add(Calendar.DATE, 1);
}
Intent intent = new Intent(events_main.this, events_receiver.class);
intent.putExtra("type",type);
intent.putExtra("note",note);
intent.putExtra("id", id);
PendingIntent dog1 = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarm1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm1.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
Toast.makeText(events_main.this, "alarms",Toast.LENGTH_SHORT).show();
}
then in the Receiver
public class events_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int id= Integer.valueOf(intent.getStringExtra("id"));
String note=intent.getStringExtra("note");
String type=intent.getStringExtra("type");
NotificationManager notificationManager2=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent dog_intent2=new Intent(context,HomeActivity.class);
dog_intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent dog_pending2=PendingIntent.getActivity(context, id,dog_intent2, PendingIntent.FLAG_ONE_SHOT);;
NotificationCompat.Builder builder2=new NotificationCompat.Builder(context)
.setContentIntent(dog_pending2)
.setSmallIcon(R.drawable.ic_action_prof_breed_icon)
.setSound(Uri.parse("android.resource://" +context.getPackageName()+ "/" + R.raw.dog))
.setContentTitle("Pet Guide 101")
.setContentText(type)
.setContentText(note)
.setVibrate(new long[] { 1000, 1000})
.setAutoCancel(true);
notificationManager2.notify(id,builder2.build());
}
}
But for some reason the alarm doesn't get triggered. When I test the code I do get the data from the database but the alarm still doesn't get executed. If you can look it up, please tell me if I'm doing it wrong especially the part of passing the unique id into the receiver.
public class SchedulerSetupReceiver extends WakefulBroadcastReceiver {
private static final String APP_TAG = "com.hascode.android";
private static final int EXEC_INTERVAL = 10 * 1000;
DBhelper dbhelper;
#Override
public void onReceive(final Context ctx, Intent intent) {
Log.d(APP_TAG, "SchedulerSetupReceiver.onReceive() called");
dbhelper = new DBhelper(ctx);
String[] ID = dbhelper.FetchAllID();
String[] time = dbhelper.FetchAlltime();
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY, 16);
calendar.set(calendar.MINUTE, 22);
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
long sdl = calendar.getTimeInMillis();
for (int k = 0; k < ID.length; k++) {
intent = new Intent(ctx, SchedulerEventReceiver.class);
// Loop counter `i` is used as a `requestCode`
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, k,
intent, 0);
// Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, sdl,
pendingIntent);
intentArray.add(pendingIntent);
}
}
This is My code for Alarm i want to set Alarm for particular time But its not trigger when time completed i have use calendar and i have set to fire 4:20 minute Pm for that i have add in Hour 16 and in minute 20 but its not triggered when Device time reach 4.20 Pm please tell me what i doing mistake
Try this
alarmManager.set(AlarmManager.RTC_WAKEUP, sdl,
pendingIntent);
Make sure that you have registered the broadcast receiver in Manifest.
<receiver android:name=".SchedulerEventReceiver"/>
And provide alarm permission as well.
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
I think you forgot to the tell the Calendar what day is today.
calendar.setTimeInMillis(System.currentTimeMillis());
I'm making an app that stores medicines data in an SQLite database in order to send to the user notifications when it's time to take them.
I already created the BroadcastReceiver class and managed the notification Intent.
The Calendar.set() function is called when I add the time (hh:mm:ss) in the database but the problem is that every time I set the time in the TimePicker dialog, the notification is sent instantly, at regardless from time.
Here is the setAlarm function from the activity where I store the time and the other stuff:
public void setAlarm()
{
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Calendar calendar = Calendar.getInstance();
char[] sTime = TimeBtn.getText().toString().toCharArray();
if(sTime[0] == '0')
{
calendar.set(Calendar.HOUR_OF_DAY, sTime[1]);
}
else
{
String tmp = "";
tmp += sTime[0];
tmp += sTime[1];
int hour = Integer.parseInt(tmp);
calendar.set(Calendar.HOUR_OF_DAY, hour);
}
if(sTime[3] == '0')
{
calendar.set(Calendar.MINUTE, sTime[4]);
}
else
{
String tmp = "";
tmp += sTime[3];
tmp += sTime[4];
int minute = Integer.parseInt(tmp);
calendar.set(Calendar.MINUTE, minute);
}
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("mName", mName);
intent.putExtra("mFormat", mFormat);
sendBroadcast(intent);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
The two lines of code below:
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Just takes data from the EditText fields then put in an Intent to manage them in the notification building.
In order to set the time to the Calendar variable, I take the text from the TimeBtn button that consists in the time string itself. I just set it when I pick the time from the TimePicker dialog.
Then I cast it in a char array in order to split hour and minute values and I put them in the calendar.set() function, distinguishing if the value starts with 0 to avoid an octal conversion when I cast them to int.
Once the time has been set, the AlarmReceiver class (extends BroadcastReceiver) does the following:
#Override
public void onReceive(Context context, Intent intent) {
String mName = intent.getStringExtra("mName");
String mFormat = intent.getStringExtra("mFormat");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
builder.setTicker("It's pill time!");
builder.setContentTitle(mName);
builder.setContentText(mFormat);
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
nManager.notify(0, notification);
}
There aren't compilation errors, I just can't spot the issue.
Thanks in advance for any help!
Try replacing
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
with
aManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+calendar.getTimeInMillis(), pIntent);
I have used following code in android application to set up Notification(Alarm) using AlarmManager.
public void setAlarm() {
Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(40000), pendingIntent);
}
Or should I use following code
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 21);
calendar.set(Calendar.HOUR_OF_DAY,11);
calendar.set(Calendar.MINUTE, 15);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
I want to set (notification)alarm at this specific time : 11:15AM on 21-March-2015
Can any one help me to set this?
First you need to use Calendar to set your date something like:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.DAY_OF_MONTH, 15);
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 15);
And then in your setAlarm() method you need to set the alarm only once. You don't need to repeat it so:
public void setAlarm() {
Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent);
}
Use alarm manager with service.
Service will introduce in manifest file.
Please follow below tutorial care fully.
A. http://nnish.com/2014/12/16/scheduled-notifications-in-android-using-alarm-manager/
B. http://androidideasblog.blogspot.co.uk/2011/07/alarmmanager-and-notificationmanager.html
C. https://github.com/benbahrenburg/benCoding.AlarmManager
D. http://www.banane.com/2014/05/07/simple-example-of-scheduled-self-clearing-android-notifications/
I hope it will help for you.
Run one thread every second and compare your specified time with current time, and if matches set notification.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm aa");
String dateTimeinSrting = "21-Mar-2015 11:15 am";
try {
Date dateTime = formatter.parse(dateTimeInString);
} catch (ParseException e) {
e.printStackTrace();
}
float dateTimeInMillis = dateTime.getTime();
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
Calendar calendar;
if(Float.compare(dateTimeInMillis, calendar.getTimeInMillis())){
//Set the notification here
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);