convert string to long triggerAtMilli - android

I am developing an alarm and I need to retrieve times from a database.
The code explains how I iterate through my database and retrieve the hour and minutes and then set it in calendar.
How can I set that function to always be working and looping in my database to compare with the current time and then ring?
what about requestcode? I have read that it's important and I should take the id of the row in my database and put it requestcode.
private void ringalarms(){
Cursor data = myDB.getListContents();
int hr,mt = 0;
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final Calendar calendar = Calendar.getInstance();
final Intent myIntent = new Intent(this.context, Alarm_Receiver.class);
data.moveToFirst();
while (!data.isAfterLast()) {
hr=Integer.parseInt(data.getString(0));
mt=Integer.parseInt(data.getString(1));
calendar.set(Calendar.HOUR_OF_DAY, hr);
calendar.set(Calendar.MINUTE, mt);
myIntent.putExtra("extra", "yes");
//myIntent.putExtra("id", i);
pending_intent = PendingIntent.getBroadcast(Add_Alarm.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pending_intent);
data.moveToNext();
}
}
and
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Hour, Minutes FROM " + TABLE_NAME, null);
return data;
}

You can use a variety of options for scheduling a background task.
For more info look into Service, JobScheduler and AlarmManager

Related

how to set multiple alarms using sqlite data?

I am new to android ,here I am developing an alarm app for my working knowledge .
I have completed the following :
creating alarms and storing it into sqlite database.
Fetching all the alarms which has the status as active .
I have tried many stackoverflow post and their solutions and other blog posts which related to my doubt but I can't get a solution for my problem .
What is my problem is I am receiving number of alarm timings from sqlite database which I have set it before and I want to set all the alarms on the stored time .
Here I don't know how to set it .
Can anyone help me to set the multiple alarms .
I am really looking for someone's help to learn and experience these things please help me .
Thanks.
You need Alarm Manager and Pending Intent more.
for (int i = 0; i < ActivemyAlarms.size(); i++) {
int mHour = 0,mMin=0;
String amPm = null;
int mAlarmId = ActivemyAlarms.get(i).getALARM_ID(); //each alarm has an unique Id ,for differentiate one from another
String mAlarmTime = ActivemyAlarms.get(i).getALARM_TIME(); // alarm time (11:12:AM)
if (!(mAlarmTime == null)) {
String mtime = mAlarmTime; // alarm time format is 12hr format (ex : 11:12:AM)
String[] time = mtime.split(":");
mHour = Integer.parseInt(time[0].trim()); // get 11 hour
mMin = Integer.parseInt(time[1].trim()); // get 12 min
amPm = ((time[2].trim()));
}
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY, amPm!=null && amPm.equalsIgnoreCase("pm")?(mHour+12):mHour);
calendar.set(calendar.MINUTE, mMin);
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
Intent intent = new Intent(this,AlarmReceiver.class); //calling my Alarm service class which plays a music on the specific time
final int _id = (int) System.currentTimeMillis(); // get calendar instance
//Use Alarm manager and Pending Intent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
And to cancel any Alarm call alarmManager.cancel(PendingIntent) like;
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.cancel(alarmIntent);

Android Alarm Manager - alarm firing on random time

Im a just new in android and im currently working on scheduler app.This is my code on setting alarm using SQLite db values.
My problem here is that the alarm is triggering on random time.
public void startAlarm() throws ParseException {
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String time = sdf.format(dt);
String start_time;
Calendar sCalendar = Calendar.getInstance();
String dayLongName = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
String checktime = "Select * from SCHEDULE where week_day='"+dayLongName+"'";
Cursor cursor = sqLiteDatabase.rawQuery(checktime, null);
if(cursor.moveToNext()) {
start_time = cursor.getString(cursor.getColumnIndex(DatabaseHelper.STARTTIME));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a",Locale.getDefault());
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("hh:mm",Locale.getDefault());
Date milli =simpleDateFormat2.parse(start_time);
String milli2 = simpleDateFormat2.format(milli);
Date timeparsed1 = simpleDateFormat.parse(start_time);
String timeparsed2 = simpleDateFormat.format(timeparsed1);
String s = milli2;
Pattern p = Pattern.compile("(\\d+):(\\d+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int hrs = Integer.parseInt(m.group(1));
int min = Integer.parseInt(m.group(2));
long ms = (long) hrs * 60 * 60 * 1000 + min * 60 * 1000;
// System.out.println("hrs=" + hrs + " min=" + min + " ms=" + ms);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, ms , pendingIntent);
//Toast.makeText(getApplicationContext(),String.valueOf(ms),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Bad Format",Toast.LENGTH_SHORT).show();
}
}
After Android 4.4, Google has introduced OS power management mechanism to minimize power use. Try adding a version checking in your code similar to the one below. If the version is KitKat and above, use setExact(). Otherwise use set().
See example below:
//For Android version 4.4 up, use setExact() for the alarm
//otherwise use set()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + syncInterval * 1000, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + syncInterval * 1000, pendingIntent);
}
Documentation reference here
Try this set of code your service never going to stop it works for me. "setInexactReapeating" not working in many of the lollipop and marshmallows devices once it started then lose control over the service this will help you out.
if (android.os.Build.VERSION.SDK_INT >= 23)
{
piLR = PendingIntent.getBroadcast(context, 0, intentLR,
PendingIntent.FLAG_UPDATE_CURRENT);
amLR.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
interval, piLR);
}
else if (android.os.Build.VERSION.SDK_INT >= 19
&& android.os.Build.VERSION.SDK_INT < 23)
{
piLR = PendingIntent.getBroadcast(context, 0, intentLR,
PendingIntent.FLAG_UPDATE_CURRENT);
amLR.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), interval, piLR);
}
else
{
amLR.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), interval, piLR);
}

Alarm is not Fired when i set time in android

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());

Use calendar to set alarm notification android

I am trying to get a notification to pop up based on the user date and time they put in. Here is my code for getting the time values
// String GetRawDate Gets The User Value For Date//
String getRawDate = date.getText().toString();
// String SplitDate Splits The Date Into Three Separate Ints//
String[] splitDate = getRawDate.split("/");
// Int GetMonth Gets The Value Of The Month//
int getMonth = Integer.parseInt(splitDate[0]);
// Int GetDay Gets The Value Of The Day//
int getDay = Integer.parseInt(splitDate[1]);
// Int GetYear Gets The Value Of The Year//
int getYear = Integer.parseInt(splitDate[2]);
// Get Military Start Time//
String test = military_start_time;
// Split It//
String[] splitStartTime = test.split(":");
// Get Hour In Integer Form
int getHour = Integer.parseInt(splitStartTime[0]);
// Get Minute In Integer Form//
int getMinute = Integer.parseInt(splitStartTime[1]);
From here I add these values to calendar
// Gets Calendar Instance//
Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, getMonth);
cal.set(Calendar.YEAR, getYear);
cal.set(Calendar.DAY_OF_MONTH, getDay);
cal.set(Calendar.HOUR_OF_DAY, getHour);
cal.set(Calendar.MINUTE, getMinute);
Then I set my alarm
// Intent To Start Notification After X Seconds//
Intent alertIntent = new Intent(this, ReminderService.class);
alertIntent.putExtra("name", name.getText().toString());
alertIntent.putExtra("time", starttime.getText().toString());
// Defines Alarm Manager//
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
// Sets Alarm Manager//
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), PendingIntent.getBroadcast(this, 1,
alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
// Starts Activity ListView//
Intent b = new Intent(this, Reminders.class);
startActivity(b);
overridePendingTransition(R.anim.slid_in, R.anim.slid_out);
Say the user has the date of 6/4/15 and the Time 22:10 I want the notification to show up on this time. For some reason it shows up about 5 seconds after the code is run through. Anybody know what I am doing wrong with the alarm?
try using
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1,
alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
P.S: Needs min API:19

Notification Message Instantly Fired - Android

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);

Categories

Resources