How to set some alarms using AlarmManager? - java

I'm making Alarm Application for Android. I wanna set more alarms using AlarmManager. How can I do it? As far as I know, I need to use PendingIntent with different request code to set some alarms. I was trying to increment a static variable and I did it but if user reload the application the variable has request code as zero. How can I set some alarms even after a reloading my application?
I have one activity
public class NewAlarmActivity extends AppCompatActivity {
private Calendar calendar;
private static int REQUEST_CODE_ALARM = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_alarm);
showTimePickerDialog();
FloatingActionButton floatingActionButton = findViewById(R.id.fb_save_alarm);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAlarm();
}
});
}
// set time for an alarm
private void showTimePickerDialog() {
calendar = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(NewAlarmActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
}
}, Calendar.HOUR_OF_DAY, Calendar.MINUTE, true);
timePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
timePickerDialog.show();
}
// get full time like a '05:45'
private String getFullTime(int hour, int minute) {
String h = String.valueOf(hour);
String m = String.valueOf(minute);
if (hour < 10) h = "0" + hour;
if (minute < 10) m = "0" + minute;
return h + ":" + m;
}
private void saveAlarm() {
setAlarm();
insertIntoSQLite();
finish();
}
private void setAlarm() {
Intent intent = new Intent(NewAlarmActivity.this, AlarmReceiver.class);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), ++REQUEST_CODE_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
private void insertIntoSQLite() {
DBHelper dbHelper = new DBHelper(NewAlarmActivity.this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("time", getFullTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
contentValues.put("description", et_description.getText().toString());
database.insert("alarm", null, contentValues);
dbHelper.close();
}
}

You can save small data to sharedPreference.
To save your REQUEST_CODE_ALARM value do this
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("Request_code", REQUEST_CODE_ALARM);
editor.apply()
To retrieve it
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int Request_code = prefs.getInt("REQUEST_CODE_ALARM", 0); //0 is the default value.
I dont suggest you to use SQL database for this purpose because SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.

Alarm manager will not be exact above api 19.
Try using Workmanager.

Related

Broadcast Receivers can not get new values from new intent and show the previous values

I have alarm manager . when user click on add button , user select time , date and fill title and other ... and after this . I save this into database and show this values into recycle view .
I get values and save them into database like this :
saveAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String mTitle = title.getText().toString();
final String mDate = date;
final String mTime = time;
final String mRepeat = getrepeat.getText().toString();
final String mReport = single_choice_selected_report_as;
if (isAnyStringNullOrEmpty(mTitle, mDate, mTime, mRepeat, mReport)) {
Snackbar snackbar = Snackbar.make(mainLayout, "", Snackbar.LENGTH_LONG);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
TextView textView = (TextView) layout.findViewById(com.google.android.material.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);
View snackView = LayoutInflater.from(SetAlarmActivity.this).inflate(R.layout.custom_toast, null, false);
TextView txtNoticToExit = (TextView) snackView.findViewById(R.id.txtCustomToast);
txtNoticToExit.setText(getResources().getString(R.string.fill_field));
txtNoticToExit.setTypeface(Apps.font);
layout.setPadding(0, 0, 0, 0);
layout.addView(snackView, 0);
snackbar.show();
} else {
if (editMode) {
Alarm alarm = new Alarm(id, mTitle, mDate, mTime, mRepeat, mReport, active);
mDatabase.updateAlarm(alarm);
} else {
Alarm alarm = new Alarm(mTitle, mDate, mTime, mRepeat, mReport, 0);
mDatabase.addAlarm(alarm);
}
Intent intent = new Intent(SetAlarmActivity.this, AlarmActivity.class);
startActivity(intent);
SetAlarmActivity.this.finish();
}
}
In row of my recycle view I have a button to active this item to alarm base on the time .
holder.toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int test = alarm.getActive();
state = !state;
if (test == 0) {
holder.toggleButton.setBackgroundResource(R.drawable.on);
holder.row.setBackgroundResource(R.drawable.purple_row);
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.white));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(1);
String strTime = alarm.getTime();
String[] timeRemoveSpace = strTime.split(" ");
String[] splitTime = timeRemoveSpace[0].split(":");
hour = getHour(strTime);
mintue = Integer.parseInt(splitTime[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, mintue);
calendar.set(Calendar.SECOND, 00);
Long date = calendar.getTimeInMillis();
StartAlarm(alarm.getId(), alarm, date);
} else {
holder.row.setBackgroundResource(R.drawable.white_row);
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon_black);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(0);
}
mDatabase.updateActive(state, alarm.getId());
notifyDataSetChanged();
}
});
and send intent into broatcast :
public void StartAlarm(int id, Alarm alarm, Long time) {
Intent intent = new Intent(context, MyReceiver.class);
intent.setAction("com.nooshindroid.yastashir");
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TITLE, alarm.getTitle());
bundle.putString(EXTRA_ALARM_DATE, alarm.getDate());
bundle.putString(EXTRA_REPORT, alarm.getReport());
bundle.putString(EXTRA_REPEAT, alarm.getRepeat());
intent.putExtras(bundle);
pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if ("بدون تکرار".equals(alarm.getRepeat())) {
Log.i("ShowMeTime", "111111");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
}
} else {
Log.i("ShowMeTime", "222222");
switch (alarm.getRepeat()) {
case "هر ساعت":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent);
break;
case "هر روز":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pendingIntent);
break;
case "هر هفته":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 7, pendingIntent);
break;
case "هر ماه":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 30, pendingIntent);
break;
}
}
}
all thins is ok until I want to edit , Once I edit my values and all these repeat , broad cast show the old values .
this my Receiver :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//and doing something
if (intent.getAction().equals("com.nooshindroid.yastashir")) {
String title = intent.getExtras().getString(EXTRA_TITLE);
Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
Log.i("khhhhhhhhhhhhhhh", "Started >>>>>>>"+title);
}
}
}
Why this happen ? any help?

Set multiple Alarms with multiple dates from a ArrayList

In my Application i need to Start after Reboot all the Alarms that i have set befor by using the dates in my Arraylist class that i have saved by sharedprefs. But only the one is set by the Alarmmanager. I used a BroadcastReciver and a for loop.
ArrayList<DateList1> dateses;
Date dateFromLog;
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("The Selected date", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("Date0list", null);
Type type = new TypeToken<ArrayList<DateList1>>() {
}.getType();
dateses = gson.fromJson(json, type);
if (dateses == null) {
dateses = new ArrayList<>();
}
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
Calendar calendar = Calendar.getInstance();
for (int i = 0; i<dateses.size(); i++){
calendar.setTime(dateses.get(i).getDate1());
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent1, PendingIntent.FLAG_ONE_SHOT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
intentArray.add(pendingIntent);
}
}
}
And here is how i add the Date to the Arraylist
ArrayList<DateList1> Dates = new ArrayList<>();
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.data_picker);
einfüGGen = (Button) findViewById(R.id.button3);
datums = (EditText) findViewById(R.id.datums);
fachs = (EditText) findViewById(R.id.fachs);
themens = (EditText) findViewById(R.id.themens);
GG = (TextView) findViewById((R.id.textView));
einfüGGen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra("datum", datums.getText().toString());
resultIntent.putExtra("fach", fachs.getText().toString());
resultIntent.putExtra("themen", themens.getText().toString());
setResult(RESULT_OK, resultIntent);
finish();
int y = Dates.size();
for (int i = 0; i<Dates.size(); i++){
Toast.makeText(EingabeFeld.this,"SOOOOSSS"+y,Toast.LENGTH_LONG).show();
}
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Toast.makeText(EingabeFeld.this, "Die Erinnerung wurde festgelegt für den "+dayOfMonth+"/"+month+"/"+year, Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
c.set(year,month,dayOfMonth);
c.set(Calendar.HOUR_OF_DAY,15);
c.set(Calendar.MINUTE,20);
c.set(Calendar.SECOND,0);
Date date = c.getTime();
Dates.add(1,new DateList1(date));
startAlarm(c);
saveData();
Here is the actual class for the arraylist
public Date date1;
public DateList1(Date date){
date1 = date;
}
public Date getDate1() {
return date1;
}
}
I Hope this is going to see Someone and Thanks in Advance
I have Solved it :D.
I did the adding to the ArrayList and the saving part in my MainActivity,and got the long by the startActivityForResult Method to my MainActivity from my SecondActivity.
Thanks for those who tried to help me,i really like you guys and have a nice day with errorless Code ;D

Android Alarm firing instantly when I set alarm on earlier hour or after midnight [duplicate]

This question already has an answer here:
android prevent immediate trigger of alarm service if alarm time has passed for the day
(1 answer)
Closed 4 years ago.
Im creating my first app in Android Studio. My Alarm Clock is working almost well, but when I will set Alarm to hour earlier than current or after midnight my alarm is firing instantly. For example, current time is 17:00, when I set alarm for 17:05 everything is fine, but when alarm is for 16:00 or 00:05 alarm is firing instantly. I will be thankful for all your advices. Here is my code:
Alarm.java
public class Alarm extends AppCompatActivity {
private TimePicker timePicker;
private Button vibrationButton;
private Button soundButton;
private Button noteButton;
private Button saveButton;
private Button cancelButton;
private CheckBox wifiCheckBox;
private CheckBox soundCheckBox;
private CheckBox bluetoothCheckBox;
private TextView textView;
private BluetoothAdapter mBluetoothAdapter;
private WifiManager wiFi;
private AudioManager audioManager;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private Intent intent;
private int hour;
private int minute;
private String minuteString;
private String hourString;
private void turnOnWifi() {
if (wifiCheckBox.isChecked())
wiFi.setWifiEnabled(true);
}
private void turnOnBluetooth() {
if (bluetoothCheckBox.isChecked())
mBluetoothAdapter.enable();
}
private void turnOnSound() {
if (soundCheckBox.isChecked())
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
private void notification() {
Intent intentNotification = new Intent(this.getApplicationContext(),Alarm.class);
PendingIntent pendingIntentNotification = PendingIntent.getActivity(this, 0, intentNotification, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("Alarm")
.setContentText("Next alarm: " + hourString + ":" + minuteString)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(false)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
notificationManager.notify(0, notification);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
timePicker = findViewById(R.id.timePicker);
vibrationButton = findViewById(R.id.vibrationButton);
soundButton = findViewById(R.id.soundButton);
noteButton = findViewById(R.id.noteButton);
saveButton = findViewById(R.id.saveButton);
cancelButton = findViewById(R.id.cancelButton);
wifiCheckBox = findViewById(R.id.wifiCheckBox);
soundCheckBox = findViewById(R.id.soundCheckBox);
bluetoothCheckBox = findViewById(R.id.bluetoothCheckBox);
textView = findViewById(R.id.textView);
wiFi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, AlarmReceiver.class);
timePicker.setIs24HourView(true);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
if (calendar.before(Calendar.getInstance()))
calendar.add(Calendar.DATE, 1);
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
calendar.set(Calendar.MINUTE, timePicker.getMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
hourString = String.valueOf(hour);
minuteString = String.valueOf(minute);
if (hour == 0)
hourString = "0" + hourString;
if (minute < 10)
minuteString = "0" + minuteString;
textView.setText("Next alarm: " + hourString + ":" + minuteString);
intent.putExtra("extra", "on");
setAlarm(calendar.getTimeInMillis());
// notification();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Alarm off!");
alarmManager.cancel(pendingIntent);
intent.putExtra("extra", "off");
sendBroadcast(intent);
// notificationManager.cancel(0);
}
});
}
private void setAlarm(long timeInMillis) {
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("test","test123");
String getState = intent.getExtras().getString("extra");
Log.e("Key is: ", getState);
Intent intentService = new Intent(context, RingtoneService.class);
intentService.putExtra("extra", getState);
context.startService(intentService);
}
}
RingtoneService.java
public class RingtoneService extends Service {
private MediaPlayer mediaPlayer;
boolean isRunning;
int startId;
#Override
public void onDestroy() {
Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
this.isRunning = false;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
String state = intent.getExtras().getString("extra");
assert state != null;
switch (state) {
case "on":
startId = 1;
break;
case "off":
startId = 0;
break;
default:
startId = 0;
break;
}
if (!this.isRunning && startId == 1){
mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
this.isRunning = true;
this.startId = 0;
}
else if (this.isRunning && startId == 0){
mediaPlayer.stop();
mediaPlayer.reset();
this.isRunning = false;
this.startId = 0;
}
else if (!this.isRunning && startId == 0){
this.isRunning = false;
this.startId = 0;
}
else if (this.isRunning && startId == 1){
this.isRunning = true;
this.startId = 1;
}
return START_NOT_STICKY;
}
}
Of course it does... It's meant to work so.
Android recognizes that the time is past, so it will fire the alarm, even if it's late.
You can make sure that the time set for the alarm is after the current time. Just calculate this difference:
int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
If diff is greater than 0, then add a day to your calendar (targetCal)
Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
if(calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingDinnerIntent);

How to show Toast in Desired date with AlarmManager on Android

In my application I want show Toast in Desired date. For this I know I should use AlarmManager.
And for this AlarmManager I find source code from internet.
In this source give time from user with time picker but I want get time static.
I want show Toast in below date :
Date : 2017-10-26
Time : 06:49:59
MainActivity codes:
public class MainActivity extends AppCompatActivity {
//the timepicker object
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the timepicker object
timePicker = (TimePicker) findViewById(R.id.timePicker);
//attaching clicklistener on button
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//We need a calendar object to get the specified time in millis
//as the alarm manager method takes time in millis to setup the alarm
Calendar calendar = Calendar.getInstance();
if (android.os.Build.VERSION.SDK_INT >= 23) {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(), timePicker.getMinute(), 0);
} else {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
}
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
Broadcast codes:
public class MyAlarm extends BroadcastReceiver {
//the method will be fired when the alarm is triggerred
#Override
public void onReceive(Context context, Intent intent) {
//you can check the log that it is fired
//Here we are actually not doing anything
//but you can do any task here that you want to be done at a specific time everyday
Toast.makeText(context, "Alarm just fired", Toast.LENGTH_SHORT).show();
}
}
How can I it? I am amateur, please help me <3
Create a date with your choice and pass it to your method setAlarm()
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "26-10-2017 06:49:59";
long alarmDate = 0L;
try {
Date d = sdf.parse(dateInString);
alarmDate = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
Try this code
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minutes);
setAlarm(calendar.getTimeInMillis());
}
}, hr1, min1, false).show();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = new GregorianCalendar(2017, 10, 26, 6, 49, 59);
setAlarm(calendar.getTimeInMillis());
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the alarm that will be fired once
am.set(AlarmManager.RTC, time, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
See GregorianCalendar

How to pass the Alarm value to Alarm Receiver

I tried to develop a sample Alarm Application. I was searched Google and SC, most of the examples confusing me. I have done with my code, but why it failed to pass the alarm value to the Alarm receiver.
Please help me. Thank you for your concern.
Here is my code.
public class ReminderFragment extends Fragment {
Button buttonstartSetDialog;
TextView txt_time;
Context ctx;
final static int RQS_1 = 1;
public ReminderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_reminder, container, false);
txt_time = (TextView) v.findViewById(R.id.txt_time);
buttonstartSetDialog = (Button) v.findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// textAlarmPrompt.setText("");
showTimePicker();
}
});
return v;
}
private void showTimePicker() {
// DatePickerFragment date = new DatePickerFragment();
TimePickerFragment time = new TimePickerFragment();
Calendar calendar = Calendar.getInstance();
Calendar calSet = (Calendar) calendar.clone();
Bundle args = new Bundle();
args.putInt("hour", calendar.HOUR_OF_DAY);
args.putInt("month", calendar.get(Calendar.MONTH));
args.putInt("minute", calendar.get(Calendar.MINUTE));
time.setArguments(args);
time.setCallBack(ontime);
time.show(getFragmentManager(), "Time Picker");
}
OnTimeSetListener ontime = new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
private MediaPlayer mMediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.", Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment {
OnTimeSetListener onTimeSet;
public TimePickerFragment() {
}
public void setCallBack(OnTimeSetListener ontime) {
onTimeSet = ontime;
}
#SuppressLint("NewApi")
private int hour, minute;
public void setArguments(Bundle args) {
super.setArguments(args);
hour = args.getInt("hour");
minute = args.getInt("minute");
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new TimePickerDialog(getActivity(), onTimeSet, hour, minute, false);
}
}
Pass the values by
intent .putExtra("test", "ValueReceived");
and then in onReceive() get the value by
intent.getStringExtra("test")
Try with
OnTimeSetListener ontime = new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
intent.putExtra("time_value",String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
You need to convert the selected time in long value (milliseconds)
use the below code to do this.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, Calendar.PM); // set AM or PM
long timeInMillis = calendar.getTimeInMillis();
and then pass this value timeInMillis in
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);

Categories

Resources