How to popup Alarm Message without any activity in background? - android

In my android i app i can alarm functionality and as well logout functionality. After setting my alarm time i am exiting the app by clicking the logout button.
I am using
ExitActivity.this.finish();
Intent intent1 = new Intent(ExitActivity.this,PinActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent1);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
this code to exit the app,which goes to home pin screen and after that it launches the home screen. This is because when i am coming back to my app it launches the pinscreen. Alarm working exactly what i want but while alarm popup message it has the pinactivity in the background(which i don't want). I wan't to get rid out of the pin activity in the background.
This is my receiver class?
public class ShortTimeEntryReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Alarm Working", Toast.LENGTH_SHORT).show();
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
Intent newIntent = new Intent(context, ReminderPopupMessage.class);
newIntent.putExtra("alarm_message", message);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
How do i do that?
Thanks for your help guys..

You should use Alarm Manager to set alarms in Android. The alarm manager holds your alarm and fire an pending intent on alarm time.
First create a pending intent like this :
pendingIntent = PendingIntent.getService(CONTEXT, ALARM_ID, INTENT_TO_LAUNCH, 0);
Then use this pending intent to set an Alarm like this :
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, ALARM_TIME, pendingIntent);
This will start the pending intent at given time.
To remove an alarm you have to recreate the same Pending Intent with same ALARM_ID :
alarmManager.cancel(pendingIntent);

First create a pending intent like this :
pendingIntent = PendingIntent.getService(context, alarm_id, Pass your data with intent, PendingIntent.FLAG_UPDATE_CURRENT);
Set an Alarm like this :
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//19 4.4and above api level
am.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + AlarmManager.INTERVAL_DAY, sender);
} else {
//below 19 4.4
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + AlarmManager.INTERVAL_DAY, sender);
}
This will start the pending intent at given time.
To remove an alarm you have to Use the same Pending Intent with same ALARM_ID:
am.cancel(pendingIntent);
Now You need to create One Service to catch your Alarm.

Related

How to correctly cancel an AlarmClock alarm set by AlarmManager in the Clock app?

This question already has answers here, here and here. But they were not confirmed by OPs to be working, and in my case, the alarm set by the same PendingIntent doesn't get canceled. Is there a way to cancel an AlarmClock alarm?
#Override
protected void onHandleIntent(#Nullable Intent i) {
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
i.putExtra(AlarmClock.EXTRA_HOUR, 6);
i.putExtra(AlarmClock.EXTRA_MINUTES, 0);
i.putExtra(AlarmClock.EXTRA_MESSAGE, "Good Morning");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getActivity(
this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
alarmIntent);
Log.d(TAG, "Alarm set");
try {
Thread.sleep(15000);
alarmMgr.cancel(alarmIntent);
Log.i(TAG, "Alarm canceled");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This code outputs as expected:
Alarm set
Alarm canceled
But it does not cancel the alarm that was set. What am I doing wrong?
So, I found that I needed to use ACTION_DISMISS_ALARM instead of ACTION_SET_ALARM. It lets you cancel already set alarms in the alarm clock.
The answers here, here, and here suggested cancelling the PendingIntent which didn't work for me and was not confirmed to be working for the question authors either.
The explanation for why cancelling the PendingIntent from AlarmManager doesn't work, I think, could be that a PendingIntent is there to let you do something or send the intent later on. Once you've already done it (already sent the intent) you can't undo it. For example, you can cancel a notification, but can't undo opening the app from the notification (the intent or action performed) as it's already done. Moreover, in my case, it was another app that I needed to unset the alarm for so maybe I shouldn't have expected to be able to undo that action.
So in order to dismiss or cancel the alarm, you need to send a new intent with the action ACTION_DISMISS_ALARM.
Replacing the try/catch block as follows sets and cancels the alarm correctly for me:
try {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
return;
}
Thread.sleep(15000);
Intent ci = new Intent(AlarmClock.ACTION_DISMISS_ALARM);
ci.setData(i.getData());
alarmIntent = PendingIntent.getActivity(this, 0, ci, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
alarmIntent);
Log.i(TAG, "Alarm cancelled");
} catch (InterruptedException e) {
e.printStackTrace();
}
However, this only works for API level 23+ and doesn't let you SKIP_UI like in ACTION_SET_ALARM.
I had the same issue and I read those thread you mentioned in your question. Yes they don't work. That's how I managed to get it working:
Set Alarm:
public static void setAlarm(Context context, int requestCode, int hour, int minute){
AlarmManager alarmManager =( AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context//same context should be used when canceling the alarm
, AlarmReceiver.class);
intent.setAction("android.intent.action.NOTIFY");
//setting FLAG_CANCEL_CURRENT makes some problems. and doest allow the cancelAlarm to work properly
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1001, intent, 0);
Calendar time = getTime(hour, minute);
//set Alarm for different API levels
if (Build.VERSION.SDK_INT >= 23){
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}
else{
alarmManager.set(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}
Cancel Alarm:
public static void cancelAlarm(Context context, int requestCode){
AlarmManager alarmManager =( AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//define the same intent and pending intent
Intent intent = new Intent(context//same activity should be used when canceling the alarm
, AlarmReceiver.class);
intent.setAction("android.intent.action.NOTIFY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1001, intent, 0);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
This works like a charm. The point is, for me, if I use the FLAG_CANCEL_CURRENT I couldn't cancel the alarm. When I deleted the flag and passed in 0 in my code, then I could successfully delete the alarm.
I am not sure about the other flags since I didn't try them. You can also try to change your flag or delete them.

Android Alarm is not working after updating time

I have set repeating alarms, it works well but when I update the time the alarm does not work. I'm using same code and flag in pending intent but creating and updating from different activity. In log it says the alarm is triggered at specific time but it is not working. can anyone say what is the problem?
Calling alarm from Insert activity:
startAlarm(Insert.this, pillName, timeInMilis, code);
Calling alarm from Edit activity:
startAlarm(Edit.this, pillName, timeInMilis, code);
Function for creating and updating alarm:
public void startAlarm(Context context, String pillName, long time, int code) {
Intent aIntent = new Intent(context, AlarmReceiver.class);
aIntent.putExtra("pillName", pillName);
aIntent.putExtra("code", code);
PendingIntent pIntent = PendingIntent.getBroadcast(context, code, aIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time,60000, pIntent);
}
Broadcast Receiver class:
public void onReceive(Context context, Intent intent) {
String pillName=intent.getExtras().getString("pillName");
MediaPlayer mediaPlayer=MediaPlayer.create(context, Settings.System.DEFAULT_NOTIFICATION_URI);
mediaPlayer.start();
Toast.makeText(context,"Testing Alarm::"+pillName,Toast.LENGTH_SHORT).show();
}
When you start before stop the AlarmManager pending intent. It's may be working well

Pending intent with different intent but same ID

I have two pending Intent to use with Alarm Manager one is:
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,0,i,PendingIntent.FLAG_CANCEL_CURRENT);
and the other is:
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,0, i,PendingIntent.FLAG_CANCEL_CURRENT);
I use these two in different methods in my application
my question is:
Are these pendingIntents differnt from each other?? because the intents are different but the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
So the easy way is test it directly by yourself.
I have tested it on my computer and here is what i got:
Are these pendingIntents different from each other?? because the intents are different but the Ids are same
-Yes they are different each other although the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
-Both of them will be triggered
Here are my code for test, you can copy and try it by yourself
Copy this method to your activity, and call it
private void setAlarmManager() {
Log.v("AlarmManager", "Configuring AlarmManager...");
Intent startIntent1 = new Intent(context, AlarmReceiverFirst.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, startIntent1, PendingIntent.FLAG_CANCEL_CURRENT);
Intent startIntent2 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, startIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 20);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Log.v("AlarmManager", "Starting AlarmManager for >= KITKAT version");
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
} else {
Log.v("AlarmManager", "Starting AlarmManager for < KITKAT version");
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
}
Log.v("AlarmManager", "AlarmManager has been started");
}
Create your first receiver class
public class AlarmReceiverFirst extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "first alarm receiver is called");
}
}
Create your second receiver class
public class AlarmReceiverSecond extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "second alarm receiver is called");
}
}
Register those receivers to your manifest
<receiver android:name=".AlarmReceiverFirst" />
<receiver android:name=".AlarmReceiverSecond" />
Not to be confused, what you called Id here is called request code. It is used for cancelling the pending intent.
Intents are just the action PendingIntent is bound to execute once it triggers. But this triggering criteria are entirely depending on PendingIntent itself and RequestCode is playing here a pretty good role to uniquely identify, manage and trigger PendingIntent.
Therefore, no matter what the Intent is, if the requestCode is repeated then the latter PendingIntent will trigger. If you need to trigger multiple PendingIntents, the requestCode must be different from each other.
You can have same name of intents but with different ids like following,
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,System.currentTimeMillis(),i,PendingIntent.FLAG_CANCEL_CURRENT);
And
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,System.currentTimeMillis(), i,PendingIntent.FLAG_CANCEL_CURRENT);
This way both the intents would be distinguished differently from each other and will get triggered.You can have any unique id instead of System.currentTimeMillis()

Creating Multiple Alarm?

Trying to create multiple Alarms using unique PendingIntent . However I am having trouble with this,
From MainActivity I press a button to set an Alarm, and the code for that is:
public void alarmSet(View view)
{
int idTime = (int) System.currentTimeMillis();
Intent intent = new Intent(MainActivity.this, AddAlarm.class);
intent.putExtra("pendInt",idTime);
startActivity(new Intent(MainActivity.this, AddAlarm.class));
}
Taking System time as unique id I am passing the value to the other activity from which I call the Broadcast to initiate alarm. Code for this Activity is:
Intent receive = getIntent();
pen = receive.getIntExtra("pendInt",0);
And here is the method in which I set the alarm.
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(AddAlarm.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, pen, alarmintent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
This works for single alarms , however it doesn't generate multiple alarms. What might be the possible reason? Any help will be appreciated. Do I need to post the Broadcast class as well ?
you are making Intent and putting extra but passing another Intent to startActivity()
just replace this
startActivity(new Intent(MainActivity.this, AddAlarm.class));
to this
startActivity(intent );

android : all of alarm were cleared how to get them back

first of all , i would like to apologize for my English its bad
all of alarm that i create by this class
Intent intent = new Intent(SETALARM.this, ALARMRECEIVER.class);
intent.putExtra("pk", pk);
sender = PendingIntent.getBroadcast(this, pk, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),60000, sender);
were cleared when device is shut off
what should i do to restore all of alarm back
thank you very much for your help
edit
here is receiver class
#Override
public void onReceive(Context context, Intent intent) {
WakeLocker.acquire(context);
pk = Integer.parseInt(intent.getExtras().get("pk").toString());
Intent intent2 = new Intent(context,ALERT.class);
intent2.putExtra("pk", pk);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
WakeLocker.release();
}}
If you mean that you lose the alarms when the device is turned off then this issue has been addressed well here
https://stackoverflow.com/a/5439320/374866

Categories

Resources