alarm not calling after reboot - android

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.
}
}
}
}

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

Android Background issues when user is in active state

I'm working on app which is required user in active feature like if user is not available on the application more than 15 min. it shows some popup on the last activity we used, when we click okay it redirects to login screen.
It is working absolutely fine when i opened back my app exactly after 15 minutes to around 30 minutes .
My problem is now, when i open my app after 45 min or more than 1 hour, it doesn't work, it doesn't show in activity popup. it just opened the last activity i used.
I tried with below code added in splash activity:
if (!isTaskRoot()
&& getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
&& getIntent().getAction() != null
&& getIntent().getAction().equals(Intent.ACTION_MAIN)) {
finish();
return;
}
Here is my BaseActivity class used for in active state checking
public class MyBaseActivity extends AppCompatActivity {
AlertDialog alertDialog;
Context context;
public static final long DISCONNECT_TIMEOUT = 900000; // 15 min = 15 * 60 * 1000 ms
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
LayoutInflater li = LayoutInflater.from(MyBaseActivity.this);
View promptsView = li.inflate(R.layout.acount_status_dialogue, null);
final TextView userInput = (TextView) promptsView.findViewById(R.id.txtTitle);
final TextView userInput1 = (TextView) promptsView.findViewById(R.id.txtTitle1);
userInput1.setText("USER IN-ACTIVE");
userInput.setText("Due to user is inactive from last 15 minutes. Please Login Again");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyBaseActivity.this,R.style.DialogLevelsStyle);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//do things
Intent i = new Intent(MyBaseActivity.this, SignInActivity.class);
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
Constant.val = 1;
AccountUtils.setValue("1");
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// Perform any required operation on disconnect
}
};
public void resetDisconnectTimer(){
Log.i("Main", "Invoking logout timer");
//disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
Log.i("Main", "cancel timer");
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
if (Constant.isAppIsInBackground(this)) {
stopDisconnectTimer();
resetDisconnectTimer();
}else {
stopDisconnectTimer();
}
super.onStop();
//stopDisconnectTimer();
}
}
Please find out my issue. thanks in advance.
Save the current time when the user put your app to background (for example in SharedPreferences), and when the user starts again your app calculate the diff and show what you want on the screen.

Android: Call function of Activity out of DialogFragment

I have a problem to call a function of my Activity out of DialogFragment. There are public functions in my MainActivity which I need to call for some calculations that are done in the DialogFragment. Everytime I try to call a function with getActivity(). there occurs the problem "Cannot resolve method".
Here is how I call the DialogFragment in the MainActivity:
FragmentManager fm = getSupportFragmentManager();
DialogWeekly dialogWeekly = new DialogWeekly();
dialogWeekly.show(getFragmentManager(), "fragment_dialogWeekly");
And this is how the DialogFragment looks like. I have added two comment lines where the mentioned problem occurs:
public class DialogReminder extends DialogFragment implements AdapterView.OnItemSelectedListener {
//--- Static Variables -----------------------------------------------------------------------//
private static final String MY_PREFS = "my_preferences";
private static Activity activity;
private static TimePicker timePicker;
private static View dialogReminderView;
//--- Integer Variables ----------------------------------------------------------------------//
private Integer weekday;
//--- String Variables -----------------------------------------------------------------------//
private String weekdayString;
//--- Other Variables ------------------------------------------------------------------------//
private SharedPreferences sharedPreferences;
/**
* Empty constructor required for DialogFragment
*/
public DialogReminder() { }
/**
* Called when a fragment is first attached to its activity.
* onCreate(Bundle) will be called after this
* #param activity Activity that is attached to this fragment
*/
public void onAttach(Activity activity) {
super.onAttach(activity);
}
//--- Override Functions ---------------------------------------------------------------------//
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_weekly, container);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
return createAlertDialog();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Integer selectedItem = parent.getSelectedItemPosition();
weekdayString = parent.getItemAtPosition(pos).toString();
// Here is the problem: savePreferences -> cannot resolve method
getActivity().savePreferences("spinnerSelectionWeekday", String.valueOf(selectedItem));
weekday = selectedItem + 2;
if (weekday == 8) {
weekday = 1;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
//--- General Activity Functions -------------------------------------------------------------//
/**
*
* #return
*/
private AlertDialog createAlertDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(getResources().getString(R.string.optionReminder));
alert.setView(dialogReminderView);
alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setReminder();
dialog.cancel();
}
});
setElementsGUI();
return alert.create();
}
/**
*
*/
private void setElementsGUI() {
Spinner spinner = (Spinner) dialogReminderView.findViewById(R.id.reminderWeekdaySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.reminderSpinnerArray, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(this);
spinner.setAdapter(adapter);
spinner.setSelection(Integer.parseInt(sharedPreferences.getString("spinnerSelectionWeekday", "0")));
}
//--- Button Functions -----------------------------------------------------------------------//
/**
*
*/
private void setReminder() {
// Here is the problem: all functions with getActivity() -> cannot resolve method
getActivity().checkReminder();
getActivity().setWeekdayReminder(weekday);
getActivity(("hour", String.valueOf(timePicker.getCurrentHour()));
getActivity().savePreferences("minute", String.valueOf(timePicker.getCurrentMinute()));
getActivity().checkReminder();
String hour = String.valueOf(getActivity().getHour());
if (hour.length() < 2) {
hour = "0" + hour;
}
String minute = String.valueOf(getActivity().getMinute());
if (minute.length() < 2) {
minute = "0" + minute;
}
String time = hour + ":" + minute;
String message = getResources().getString(R.string.reminderToast, weekdayString, time);
Toast toast = Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_LONG);
toast.show();
}
}
While getActivity() returns a MainActivity at runtime, the compiler has to assume that it's just an Activity object and that those methods don't exist (since an Activity has none of these methods). Hence the compiler error.
What you need to do is cast the Activity to a MainActivity object like so:
((MainActivity)getActivity()).savePreferences(...
In kotlin we can cast the Fragment to a MainActivity object like this
(activity as MainActivity).yourMethodeName()

Session Timeout after specific time with AlertDialog

Before referring me to other threads on this forum and marking my question as duplicate kindly read my question. I have to create a global application timeout. No matter which activity is user on, after specific amount of time the user will be displayed AlertDialog that his session has expired and he can exit or renew his session. I have read different solutions and used service as my solution.
public class InActivityTimer extends Service {
MyCounter timer;
#Override
public void onCreate() {
timer = new MyCounter(20 * 1000,1000);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer.start();
return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
Intent intent = new Intent("timeout_action");
sendBroadcast(intent);
stopSelf();
}
#Override
public void onTick(long millisUntilFinished) {
// Need AlertDialog code here
Toast.makeText(getApplicationContext(), ("Time Remaining: " + millisUntilFinished/1000)+"", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
The problem is that I can display the Toast without any problem but the AlertDialog is not displayed when called inside onFinish().
The first problem is to display the AlertDialog for whole application bearing in mind that the AlertDialog is displayed for some context. Also if somehow the AlertDialog is displayed then how to close the Application. On Activity I just close the activity by calling finish() so should I clear the Activities stack in this case?
The second complex part that I am facing is to display a popup when user click "Time remaining" link in the application which will show how much time is remaining for the Session to be timed out. This time should be exactly same as the time remaining in the service.
I can also use BroadcastReceiver and send update to the activity once the time is finished but wouldn't that be Activity specific because I want the timeout to act same regardless of which activity is user on. I want to avoid writing the same code on each activity.
Kindly guide me through with some solution.
If you use a fragment based design for your app, you can keep a root FragmentActivity in which all other elements of the app are displayed. This way you can use the context of the root FragmentActivity every time, to display your Dialog.
Additional: "Could you kindly refer to me some article.."
What you are doing is not common, and I would have to google search just like you to find any existing example similar to your case. I can however fill in a bit more detail on what I have proposed above.
If you are unfamiliar with using Fragments, read the Developer Documentation.
public class MainActivity extends FragmentActivity {
private static final int SPLASH_SCREEN_FRAGMENT = 0;
private static final int HOME_SCREEN_FRAGMENT = 1;
...
#Override
protected void onCreate(Bundle. savedInstanceState) {
super.onCreate(savedInstanceState);
// show your first fragment
Fragment splashFragment = new SplashFragment();
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, splashFragment).commit();
// Start your service using the context of your FragmentActivity
// Your FragmentActivity will always be the current activity, and you will display
// all other elements of your app inside it as fragments
Intent intent = new Intent(this, InActivityTimer.class);
startService(intent);
}
// method for switching the displayed fragment
private void fragmentSwitcher(int fragmentType) {
Fragment currentFragment = new Fragment();
switch (currentFragmentType) {
case SPLASH_SCREEN_FRAGMENT:
currentFragment = new SplashScreenFragment();
break;
case HOME_SCREEN_FRAGMENT:
currentFragment = new HomeScreenFragment();
break;
...
}
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, currentFragment).commit();
}
}
I have solved my issue with rather very simple approach.
#Override
public void onFinish() {
Intent intent = new Intent(getBaseContext(), TimeoutActivity.class);
startActivity(intent);
stopSelf();
}
and below is the onCreate method for my TimeoutActivity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContextThemeWrapper ctw = new ContextThemeWrapper(TimeoutDialogActivity.this, R.style.Theme_Base_AppCompat_Dialog_FixedSize);
final AlertDialog alertDialog = new AlertDialog.Builder(ctw).create();
alertDialog.setCancelable(false);
alertDialog.setTitle("Session Timeout !");
alertDialog.setTitle("Your session has expired.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Logout", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Renew Session", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
});
alertDialog.show();
}

Display an alert dialog box after a custom alarm rings

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.

Categories

Resources