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 !
Related
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);
Background
My application populates a list view containing list of specific times. When the user selects a specific item in the list view, the alarm is scheduled/triggered for that timing. Now I can achieve to create a notification when the alarm starts ringing. But now, I wanted to create an alert dialog box instead of notification. Also, upon the user clicking the OK button on the alert dialog box, the alarm should stop and the alert box should be closed. How can I achieve that?
Also, please explain to me which class to use to call the alert dialog box and which class should I use it to extend and where should I place my intents or pending intents to call the alert dialog box.
P.S: I have used broadcast receiver for my alarm to get scheduled at the selected time from the list of timing.
The class to schedule an alarm
public class mrvtoparanur extends Activity {
int hours,mins;
long time;
CSVAdapter mAdapter;
final static int RQS_1=1;
Calendar cal = Calendar.getInstance();
Calendar calset = (Calendar)cal.clone();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mrvtoparanur);
final ListView mList = (ListView)findViewById(R.id.mrvtoparanurlist);
mAdapter=new CSVAdapter(this,-1);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
clock clicked=mAdapter.getItem(arg2);
String [] res = clicked.getTime().split(":");
hours=Integer.parseInt(res[0]);
mins=Integer.parseInt(res[1]);
Toast.makeText(getApplicationContext(), "You selected time :"+hours+"hours and "+mins+"mins", Toast.LENGTH_SHORT).show();
ScheduleAlarm();
}
});
}
protected void ScheduleAlarm() {
// TODO Auto-generated method stub
calset.set(Calendar.HOUR_OF_DAY, hours);
calset.set(Calendar.MINUTE, mins);
calset.set(Calendar.SECOND, 0);
Long time = calset.getTimeInMillis();
Intent intentAlarm = new Intent(this, AlarmReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(this, "Reminder Set", Toast.LENGTH_SHORT).show();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Alarm receiver
public class AlarmReciever extends BroadcastReceiver
{
Context context ;
#Override
public void onReceive( Context context, Intent intent)
{
// TODO Auto-generated method stub
// here you can start an activity or service depending on your need
// for example you can start an activity to vibrate phone or to ring the phone
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();
Toast.makeText(context, "Alarm Trigerred", Toast.LENGTH_SHORT).show();
}
}
The Clock item
public class clock {
private String t;
public String getTime() {
return t;
}
public void setTime(String t) {
this.t = t;
}
}
My question is: If I have to start an alert as soon as the alarm starts ringing, should I create a separate new class file for alert dialog to display? Or can I embed the code for alert dialog in any of the class above? If i can embed it, then which class should I choose to embed the alert dialog code and from which class should I call the alert dialog?
You can create a new activity with a dialog layout when you receive your event.
But I am not sure it is a good idea to display a dialog box. The user will be annoying.
Why not keeping the notification ?
Download the android source code from https://source.android.com/ and look at the ./packages/apps/DeskClock/src/com/android/deskclock/AlarmAlertFullScreen.java code. It appears to do just what you are describing.
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().
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);
}
};
I want to use a Toast inside the CountdownTimer, but the problem is the Toast counts too slow and when the new Activity stars the Toast isn't finished counting.I know it is easier to use a TextView but I just wanted to know if it is possible.Any ideas?
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(Edt.getText().toString().length() == 0){
Toast.makeText(MainActivity.this,"What, bro?",Toast.LENGTH_LONG).show();
}else if(sec.getText().toString().length() == 0){
Toast.makeText(MainActivity.this,"When, bro?",Toast.LENGTH_LONG).show();
}else{
Event=new String(Edt.getText().toString());
final int time = Integer.parseInt(sec.getText().toString());
Intent myInt = new Intent(MainActivity.this,Receiver.class);
myInt.putExtra("key",Event);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,2,myInt,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(time*1000),pendingIntent);
new CountDownTimer(time*1000, 1000) {
public void onTick(long millisUntilFinished) {
Toast.makeText(MainActivity.this,"Alarm starts in"+ +millisUntilFinished/1000 + "seconds",Toast.LENGTH_SHORT).show();
}
public void onFinish() {
}
}.start();
}
If you mean that they stack up causing a delay then you should cancel the prior toast before showing a new one.
If you want something more fancy you could try using a PopupWindow instead to show the countdown, there you have more freedom for layout etc.
http://developer.android.com/reference/android/widget/PopupWindow.html