Display an alert dialog box after a custom alarm rings - android

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.

Related

if and return statement

I am new to Android programming, and now I'm working on an application to remind me of the schedule of my lectures. For example, a lecture starts at 12:30 and ends at 1:30 pm. The application will notify me at the date, and turn my phone into the silent mode. My application now works well, but the problem is that after the end of the lecture the app should turn back the phone into Normal mode .
my main_activity Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ring(12,21,0);
ring(12,30,1);
}
public void ring (int h,int m,int mode){
/** This intent invokes the activity DemoActivity, which in turn opens the AlertDialog window */
Intent i = new Intent("in.wptrafficanalyzer.servicealarmdemo.demoactivity");
i.putExtra("mode",mode);
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hour = h;
int minute = m;
/** Creating a calendar object corresponding to the date and time set by the user */
GregorianCalendar calendar = new GregorianCalendar(year,month,day, hour, minute);
/** Converting the date and time in to milliseconds elapsed since epoch */
long alarm_time = calendar.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.RTC_WAKEUP , alarm_time , operation);
/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
my DemoActivity code :
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
my problem is in AlertDemo code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
am = (AudioManager) getActivity().getBaseContext().getSystemService(Context.AUDIO_SERVICE);
Intent i = this.getActivity().getIntent();
int info = this.getActivity().getIntent().getIntExtra("mode", 0);
if (info == 0) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
final Ringtone ringtone = RingtoneManager.getRingtone(getContext(), uri);
ringtone.play();
handler.postDelayed(new Runnable() {
#Override
public void run() {
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}, 300000);
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
ringtone.stop();
}
});
/** Creating the alert dialog window */
return builder.create();
}
else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
the problem is missing return statement when i add the statement "return null"
This error appears(Application stopped):
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.servicealarmdemo/in.wptrafficanalyzer.servicealarmdemo.DemoActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
In case you return null, your alert object is null. Then you go ahead and ask to perform the "show" method on this object, hence the null pointer exception. Since you do it in the "onCreate" method if DemoActivity, your activity fails to start. Try to make the decision of whether to show the dialog or not beforehand, previously to creating the alert itself. Then just create (and show) the alert only when the mode is suitable (by the way, Java has booleans, why are you using integers?).
Don't do decision making in onCreateDialog method. Remove if-else block out of onCreateDialog
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
am = (AudioManager) getActivity().getBaseContext().getSystemService(Context.AUDIO_SERVICE);
Intent i = this.getActivity().getIntent();
int info = this.getActivity().getIntent().getIntExtra("mode", 0);
if (info == 0) {
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
} else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}

Activity as dialog from BroadcastReceiver over another activity

My app listens for an Intent fired by a third party app when an Activity in that app is shown. The Intent is received in a BroadcastReceiver in my app. I want to start an Activity from the BroadcastReceiver which will show as a Dialog over the existing activity (that fired the Intent).
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, ">>>>>>>>> Action:" + action);
if ("clover.intent.action.V1_ORDER_BUILD_START".equals(action)) {
Intent i = new Intent(context.getApplicationContext(), ActiveOrderActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
The Intent clover.intent.action.V1_ORDER_BUILD_START is fired by a different app which my app listens for. When this Intent is fired, an Activity is already open (see the background activity in the picture below).
Now I want to show an Activity in my app as Dialog over the already shown activity, just like the "Add Customer to Order" in the image below.
As shown in the code above, I am starting an Activity from BroadcastReceiver, but when it starts, it comes to foreground and the previous Activity is not shown.
See below for an example of what I want to achieve,
Maybe you should create
public class MyDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflaterViewObject = LayoutInflater.from(getActivity());
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View DialogView = inflaterViewObject.inflate(R.layout.dialog, null);
final AlertDialog Dialog = new AlertDialog.Builder(getActivity()).create();
Dialog.setView(DialogView);
DialogView.findViewById(R.id.dialog_YES).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your YES logic
Dialog.dismiss();
}
});
DialogView.findViewById(R.id.dialog_NO).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your NO LOGIC
Dialog.dismiss();
}
});
// return dialog object (later on .show());
return Dialog;
}
Later you write in your choosen place (in BrodcastReciever)
MyDialog dialogObject = new MyDialog();
dialogObject.show(getFragmentManager(), "tag name for the dialog fragment.");

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 !

Can I use a Toast for the CountDownTimer

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

alarm not calling after reboot

I had created a program that will create alarm for different date set manually from the date picker.
The code is working properly.but if reboot it losing the data and alarm is not working how can i overcome that
The code I used is
int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickListener setClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
/** This intent invokes the activity DemoActivity, which in turn opens the AlertDialog window */
Intent i = new Intent("in.com.example.demoactivity");
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), count++, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
/** Getting a reference to DatePicker object available in the MainActivity */
DatePicker dpDate = (DatePicker) findViewById(R.id.dp_date);
/** Getting a reference to TimePicker object available in the MainActivity */
TimePicker tpTime = (TimePicker) findViewById(R.id.tp_time);
int year = dpDate.getYear();
int month = dpDate.getMonth();
int day = dpDate.getDayOfMonth();
int hour = tpTime.getCurrentHour();
int minute = tpTime.getCurrentMinute();
GregorianCalendar calendar = new GregorianCalendar(year,month,day, hour, minute);
long alarm_time = calendar.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.RTC_WAKEUP , alarm_time , operation);
/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();
}
};
OnClickListener quitClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
};
Button btnSetAlarm = ( Button ) findViewById(R.id.btn_set_alarm);
btnSetAlarm.setOnClickListener(setClickListener);
Button btnQuitAlarm = ( Button ) findViewById(R.id.btn_quit_alarm);
btnQuitAlarm.setOnClickListener(quitClickListener);
}
From that to an activity fragment
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
from here to an activity which create an alertbox
public class AlertDemo extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
}
});
/** Creating the alert dialog window */
return builder.create();
}
/** The application should be exit, if the user presses the back button */
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
I want thealarm to be invoken even if I reboot the device,Somebody please help me to sort it out
You have to Use BroadcastReceiver in which you have to check Intent.ACTION_BOOT_COMPLETED and reset your alarm actions within Receiver. For example:
public class MyBootReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
//reset your alarm here
}
}
}
Updated:
Use share-preference to store you data, or you can use database too. I did same using share-preference, check below code:
public class MyBootReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
SharedPreferences mPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
String datetime = mPreferences.getString("date", null);
if(!TextUtils.isEmpty(datetime)) {
Utility.setNotification(context);//set your alarm here.
}
}
}
}

Categories

Resources