working with android alarmmanager - android

I have a reminder kind of app where users will set their reminders.
Most of the tutorials and example that i found were of alarm manager in which alarm is set up after specific time or at pre defined time. but how can i set it to user entered data and time. Also, there will be more than one alarms set up by the user.
All these are stored in a database and then populated in a lsitview.
This is a fragment in which user will be setting date and time: (texts "dte" and "tme" displays date and time that user has selected) and then when user clicks save button, i want to set alarm at the time that is selected by user.
Calendar calender = Calendar.getInstance();
TextView dte,tme, doit;
ImageButton cal;
EditText enteredTask;
Button save;
String taskentered, dateentered, timeentered;
tasks_Database_Operations tasksDatabaseOperations;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_task_fragment, container, false);
dte = (TextView) view.findViewById(R.id.datetv);
tme = (TextView) view.findViewById(R.id.timetv);
Log.d("LifeCycle HirakDebug", "aTF View Created");
return view;
}
#Override
public void onResume() {
super.onResume();
Log.d("LifeCycle HirakDebug", "aTF Resume");
enteredTask = (EditText) getActivity().findViewById(R.id.user_entered_task);
doit = (TextView) getActivity().findViewById(R.id.title);
cal = (ImageButton) getActivity().findViewById(R.id.select_date);
save = (Button) getActivity().findViewById(R.id.save_tsk);
save.setOnClickListener(this);
cal.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == cal) {
FragmentManager fm = getFragmentManager();
date_time_picker dTP = new date_time_picker();
dTP.setTargetFragment(this, 1);
dTP.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.myCustomDialog);
dTP.show(fm, "dTP");
Log.d("HirakDebug", "add_task_frag setDate called");
} else if (view == save) {
saveData();
Log.d("HirakDebug", "add_task_frag saveData called");
}
}
private void saveData() {
String iidd = null;
taskentered = enteredTask.getText().toString();
dateentered = dte.getText().toString();
timeentered = tme.getText().toString();
tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
long id = tasksDatabaseOperations.insertData(iidd, taskentered, dateentered, timeentered);
if (id < 0) {
Log.e("HirakDebug", "add_task_frag failed insertData operation");
} else {
Log.d("HirakDebug", "Data sent to be inserted");
}
tasksDatabaseOperations.sqLiteDatabase.close();
goBackToTaskListFragment();
}
private void goBackToTaskListFragment() {
tasksListFrag tLF = new tasksListFrag();
add_task_frag aTF = new add_task_frag();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
ft.remove(this);
ft.replace(R.id.dynamic_content, tLF, "tLF");
ft.commit();
Log.d("HirakDebug", "add_task_frag went back to taskListFrag");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1){
String date = data.getStringExtra("date");
String time = data.getStringExtra("time");
dte.setText(date);
tme.setText(time);
}
}

Perhaps Repeating Alarm the one you need to use.
Please click on the link below...
Set a Repeating Alarm
https://developer.android.com/training/scheduling/alarms.html
Code example form the link above:
Wake up the device to fire the alarm at precisely 8:30 a.m., and every 20 minutes thereafter:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);

Related

TimePicker reverse 24 hour data

Good day!
I have a Dialog class that contains TimePicker. TimePicker is set for 24hour mode. When i pick time with hour < 12 - Picker returns it with +12 hours more.
For example -
i've set 07:25 - returns 19:25. And vise-versa
if i set 19:43 - returns 07:42. And
if i set 12:01, for example - TimePicker returns idiotic 24:01.
What's problem with this tool?
Here the full code of my Dialog class:
public class TimePickerDialog extends DialogFragment {
public static final String EXTRA_TIME = "time";
#Bind(R.id.pickerTime_timePicker) TimePicker timePicker;
//// DialogFragment methods
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.picker_time, null);
ButterKnife.bind(this, view);
timePicker.setIs24HourView(true);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(getString(R.string.time_picker_dialog_label))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
//// Private methods
private void sendResult(int resultCode) {
if (getTargetFragment() == null) {
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_TIME, getTimeFromTimePicker(timePicker));
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
private Date getTimeFromTimePicker(TimePicker timePicker) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
return calendar.getTime();
}
}
Put this line,
timePicker.setCurrentHour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
below,
timePicker.setIs24HourView(true);
which will set the current time corretly.
Let me know if it works for you...
I guess, you should use calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
Just read the documentation
The provided example works for everyone, no need to bind something. Why do you need that extra logic inside the dialog? It should be responsible for picking the time. The other logic should be in your controller.

why does Just the last alarm sat have been worked

i have a project that use alarmmanager. many avtivity set alarms and then when alarm have been rise,specific activity in name of AlarmSetter that started show alarm and also set a new (next) alarm and snooz alarm(if user needs). my problem is just the last alarm setted . this mean all activity set alarm byut the last alarm set has worked .for example in alarm setter if user select snooz button then main alarm dont work(just snooz work as well = the last alarm sat).
i set alarmmanager in G class(common) and use and set alarm in activity alarm.java
This is My G Class :
public class G extends Application {
public static AlarmManager alarmManager;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
}
Alarm Setter Java IS :
public class ActivityAlarm extends ActivityMain {
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.alarmshower);
//at first reminder will start, should register next alarm time :
long MilisectoAlarmManager = mDbHelper.SetNextTime_andIsactiveYET(DrugRegID);
if (MilisectoAlarmManager != 0 && IsFor10minlater == 0) {
Intent intentMain = new Intent(G.context, ActivityAlarm.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentMain.putExtra("DrugID", String.valueOf(DrugRegID));
intentMain.putExtra("IsItFor10MinLate", String.valueOf(0));
PendingIntent pendingIntentMain = PendingIntent.getActivity(G.context, 0, intentMain, PendingIntent.FLAG_UPDATE_CURRENT);
String AA = mDbHelper.GetStartDateAlarm(DrugRegID);
Date D = new Date(MilisectoAlarmManager);
System.out.println("current Date(ms): " + MilisectoAlarmManager);
G.alarmManager.set(AlarmManager.RTC_WAKEUP, MilisectoAlarmManager, pendingIntentMain);
}
//Finished Activing Alarm Manager and switch Off Alarmn
else if (MilisectoAlarmManager == 0 && IsFor10minlater == 0) {
mDbHelper.UpdateAlarmSwitch(DrugRegID, false);
}
handler.postDelayed(r, HowLongRemainAlarm_var);
//End CountDown Finished Activity
//Procedure for 10 min later button
btn10minLater_var.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btn10minLater_var.setBackgroundColor(Color.parseColor("#1174b9"));
Intent intentFor10min = new Intent(G.context, ActivityAlarm.class);
intentFor10min.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentFor10min.putExtra("DrugID", String.valueOf(DrugRegID));
intentFor10min.putExtra("IsItFor10MinLate", String.valueOf(1));
PendingIntent pendingIntent10min = PendingIntent.getActivity(G.context, 0, intentFor10min, PendingIntent.FLAG_UPDATE_CURRENT);
G.alarmManager.set(AlarmManager.RTC_WAKEUP, new Date().getTime() + 20000, pendingIntent10min);
ActivityAlarm.this.finish();
}
});
i found asnwer ! in PendingIntent.getActivity secound parameter must have diffrent in each alarm set !

my multiple alarms does not work | android

hi i have a problem with my code in the multiple alarm . i typed my code to be work on a multiple alarms every alarm take 10 seconds to be triggered REPEATEDLY. my problem that the alarm work with just one value but although i have put a different requestCode, but it cannot bet work or i don't know how i call every one separately .
the problem is i'v try to do this--->
alarm1 with a value and a request code 0 (for example) for 10 seconds
alarm2 with a different value and a request code 1 (for example) for 10 seconds
the code do this---->
desplay an just alarm2 that i selected lately
static int HELLO_ID = 1;
boolean flag = false;
int CountMultipleAlarm = 0;
EditText edt,edt2;
Button btn;
CountDownTimer timer;
//the strings of the notifications
String titlePills = "Time to take Panadol",DescriptionPills = "Panadol";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
btn = (Button)findViewById(R.id.button1);
edt = (EditText)findViewById(R.id.editText1);
//hide the button and the edit text
btn.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String edittext= edt.getText().toString();
Pattern pat= Pattern.compile("[0-9]");
// Pattern pat= Pattern.compile("[a-zA-Z0-9]");
Matcher matcher = pat.matcher(edittext);
//*************Timer Start *************************8
//11000 = 10 seconds(11000*6*60 == 1hour)
int count = 11000;
timer = new CountDownTimer(count, 1000)
{public void onTick(long millisUntilFinished)
{
long scnds=0;
scnds=(millisUntilFinished/1000);
}
public void onFinish()
{//Alaram cooooode **********************************************************
Calendar cal = Calendar.getInstance(); //for using this you need to import java.util.Calendar;
AlarmManager am = (AlarmManager)parent.getContext().getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
//the title and the description of the notification
Intent alarmintent = new Intent(parent.getContext(), Alarm_Receiver.class);
alarmintent.putExtra("title",titlePills + "value");
alarmintent.putExtra("note","value");
//HELLO_ID is a static variable that must be initialized at the BEGINNING OF CLASS with 1;
//example:protected static int HELLO_ID =1;
PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), CountMultipleAlarm++,
alarmintent,PendingIntent.FLAG_UPDATE_CURRENT);
//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to
//AlarmReceiver Class
// Get the AlarmManager service
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
//Alarm coooooode end **************************************
intentArray.add(sender);
timer.start();
}
}.start();
//*************Timer Ends *************************8
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}import
and this is the alarm_Receiver class
public class Alarm_Receiver extends BroadcastReceiver {
String notification1 = "You Pills Time ";
private static int NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager manger = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notification1,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID,
new Intent(context, Alarm_Receiver.class), 0);
Bundle extras=intent.getExtras();
String title=extras.getString("title");
//here we get the title and description of our Notification
//
String note=extras.getString("note");
notification.setLatestEventInfo(context, note, title, contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
notification.defaults |= Notification.DEFAULT_SOUND;
//here we set the default sound for our
//notification
// The PendingIntent to launch our activity if the user selects this notification
manger.notify(NOTIFICATION_ID++, notification);
}
};
You are overwriting the old one because the request code that you use in getBroadcast() is always zero.
PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), i++, alarmintent,
PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
The value of i is always zero, because you always set it to zero before calling getBroadcast().

How can I use multiple Alarms at once - Android

Hi, I have a problem with my code.I typed my code to be work on a multiple alarms every alarm take 10 seconds to be triggered REPEATEDLY.My problem is that the alarm works with just one value but although I've put a different requestCode,but it doesn't work or I don't know how I can call every one separately .
I've tried to do this:
alarm1 with a value and a request code 0 (for example) for 10 seconds
alarm2 with a different value and a request code 1 (for example) for
10 seconds
The code does:
Display Alarm2 that I selected last.
static int HELLO_ID = 1;
boolean flag = false;
int CountMultipleAlarm = 0;
EditText edt,edt2;
Button btn;
CountDownTimer timer;
//the strings of the notifications
String titlePills = "Time to take Panadol",DescriptionPills = "Panadol";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
btn = (Button)findViewById(R.id.button1);
edt = (EditText)findViewById(R.id.editText1);
//hide the button and the edit text
btn.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String edittext= edt.getText().toString();
Pattern pat= Pattern.compile("[0-9]");
// Pattern pat= Pattern.compile("[a-zA-Z0-9]");
Matcher matcher = pat.matcher(edittext);
//*************Timer Start ******************
//11000 = 10 seconds(11000*6*60 == 1hour)
int count = 11000;
timer = new CountDownTimer(count, 1000)
{public void onTick(long millisUntilFinished)
{
long scnds=0;
scnds=(millisUntilFinished/1000);
}
public void onFinish()
//****** Alarm Code ********
Calendar cal = Calendar.getInstance();
// for using this you need to import java.util.Calendar;
AlarmManager am = (AlarmManager)parent.getContext().getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
//the title and the description of the notification
Intent alarmintent = new Intent(parent.getContext(), Alarm_Receiver.class);
alarmintent.putExtra("title",titlePills + "value");
alarmintent.putExtra("note","value");
//HELLO_ID is a static variable that must be initialized at the BEGINNING OF CLASS with 1;
//example:protected static int HELLO_ID =1;
PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), CountMultipleAlarm++,
alarmintent,PendingIntent.FLAG_UPDATE_CURRENT);
//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to
//AlarmReceiver Class
// Get the AlarmManager service
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
//Alarm coooooode end **************************************
intentArray.add(sender);
timer.start();
}
}
//************* Timer Ends *************
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}import
//Edit from Paramone: What comes after " }import " ???
alarm_Receiver class
public class Alarm_Receiver extends BroadcastReceiver {
String notification1 = "You Pills Time ";
private static int NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager manger = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notification1,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID,
new Intent(context, Alarm_Receiver.class), 0);
Bundle extras=intent.getExtras();
String title=extras.getString("title");
//here we get the title and description of our Notification
String note=extras.getString("note");
notification.setLatestEventInfo(context, note, title, contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
notification.defaults |= Notification.DEFAULT_SOUND;
//here we set the default sound for our notification
// The PendingIntent to launch our activity if the user selects this notification
manger.notify(NOTIFICATION_ID++, notification);
}
};

Calculation of current time in android

suppose I click start button and close the application but Notification is running. After five miutes I open notification then second activity opens and settext with 5 min.Again i close appliction.Then again I click on start button.suppose after 3 min i check notification it should open with 3 min not 8.but in my application it show 8 min
1:Main ACtivity where notification is start
public class MainActivity extends Activity {
final Context context=this;
private EditText timerValue;
private static final int NOTIFY_ME_ID=1337;
Intent MyIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerValue = (EditText) findViewById(R.id.timerValue111);
startButton = (Button) findViewById(R.id.startButton);
x=timerValue.getText().toString();
nman=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
startButton.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(View view) {
Long s1=(long) 0.0;
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
//Toast.makeText(MainActivity.this,timeStamp,2000).show();
Date interestingDate = new Date();
s1= interestingDate.getTime();
int seconds = (int) (s1/ 1000) % 60 ;
int minutes = (int) ((s1 /(1000*60)) % 60);
int hours = (int) ((s1 /(1000*60*60)) % 24);
Toast.makeText(MainActivity.this,"Time:"+hours+":"+minutes+":"+seconds,2000).show();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Reminder";
Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Medicine!";
String MyNotificationText = "Don't forget to take your medicine!";
MyIntent = new Intent(MainActivity.this,SecondActivity.class);
MyIntent.putExtra("s1", (long)s1);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent,0);
// x=timerValue.getText().toString();
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
});
}
}
2:Second Activity where total time is calculated
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
long p=(long) 0.0;
long s=(long) 0.0;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView text1=(TextView)findViewById(R.id.text1);
Bundle extras = getIntent().getExtras();
Date interestingDate = new Date();
s= interestingDate.getTime();
long x1=extras.getLong("s1");
p=s-x1;
int minutes = (int) ((p /(1000*60)) % 60);
text1.setText(""+minutes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
That is happening maybe because you do not close the application, so the application goes in onPause state, and your second activity is not calling the onDestroy => when you enter again in the second activty, is called the onResume method, where you do not set the TextView text

Categories

Resources