I'm using alarmmanager class to schedule notification for the user to lunch every day in a certain time but when th time comes it force stop the application
this is the setAlarm() method that i call onCreate of the main activity
public void setAlarm() {
// TODO Auto-generated method stub
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at approximately 8:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 17);
// With setInexactRepeating(), you have to use one of the AlarmManager
// interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
alarmIntent);
}
and that's the the BroadcastReceiver Class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
creatNotification(context, "Times Up", "5 Seconds Passed", "Alert");
}
private void creatNotification(Context context, String MSG, String MSgText, String MSGAlert) {
PendingIntent NotifIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
notifBuilder.setContentTitle("title").setContentText("Content")
.setTicker("Ticker").setSmallIcon(R.drawable.ic_launcher);
notifBuilder.setContentIntent(NotifIntent);
notifBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
notifBuilder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notifBuilder.build());
}
any Ideas ??
Did you define your Broadcast receiver on Manifest file?
Related
I start to combine alarm manager and notification manager on android, and this is my code:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setReminderAlarm();
}
public void setReminderAlarm() {
Intent intent = new Intent(MainActivity.this, ReminderReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ReminderReceiver.NOTIF_ID, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 59);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000L, pendingIntent);
}
ReminderReceiver.java
public static int NOTIF_ID = 101;
#Override
public void onReceive(Context context, Intent intent) {
showAlarmNotification(context);
}
public void showAlarmNotification(Context context) {
Intent intentClick = new Intent(context, MainActivity.class);
PendingIntent pendingClick = PendingIntent.getActivity(context, 0, intentClick, 0);
NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.cinema)
.setContentTitle(title)
.setContentIntent(pendingClick)
.setContentText(message)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setSound(alarmSound)
.setAutoCancel(true);
notificationManagerCompat.notify(NOTIF_ID, builder.build());
}
Every time I run the application, the notification always appears even though I have set the time. How do I prevent that?
Thank you.
The issue is you are setting the time to current day. So if you are opening your app after 6:00, your alarm manager will immediately fire.
You need to check whether the time is over 6:00 for the current day, if yes you need to change the date to the next day:
public void setReminderAlarm() {
Intent intent = new Intent(MainActivity.this, ReminderReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ReminderReceiver.NOTIF_ID, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 6
if (curHr >= 6)
{
// Since current hour is over 6, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 59);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000L, pendingIntent);
}
I have a code in which alarm manager starts a service. I have to cancel it with the specified time using a second alarm. Not a single solution that I've looked at works. My code is as follows:
void startAtInterval(int fromTime, int fromTimeMinute, int toTime, int toTimeMinute, int id1, int id2) {
// start alarm
AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, fromTime);
calendar.set(Calendar.MINUTE, fromTimeMinute);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
// stop alarm
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent1 = PendingIntent.getService(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
stopService(intent);
alarmMgr1.cancel(alarmIntent1);
}
I used FLAG_UPDATE_CURRENT and FLAG_CANCEL_CURRENT. I also tried to stopservice as I show in my code. I'm passing time from a configuration screen. I know it works because first alarm is always fired.
You should have the second alarm which cancels the service fire a BroadcastReceiver which then stops the service. This will ensure that the alarm will successfully stop the service under any circumstances, such as the app being closed.
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intentCancelService= new Intent(getApplicationContext(), StopServiceReceiver.class);
PendingIntent alarmIntent1 = PendingIntent.getBroadcast(getApplicationContext(), StopServiceReceiver.REQUEST_CODE, intentCancelService, PendingIntent.GoTestAlarmReceiver);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
Then make your BroadcastReceiver:
public class GoTestAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 123123; //whatever code just unique
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, YourServiceClassHere.class);
context.stopService(i);
}
}
Make sure to declare the receiver in your manifest:
<receiver
android:name=".StopServiceReceiver"
android:enabled="true"
android:process=":remote" />
To stop any alarm manager you have to use this:
Intent intentS = new Intent(ctx,YourService.class);
intentS.addCategory("SOMESTRING_AS_TAG");
PendingIntent senderS = PendingIntent.getService(ctx, NDX, intentS, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(senderS);
senderS.cancel();
//and this
PendingIntent senderSNew = PendingIntent.getService(ctx, NDX, intentS, 0);
am.cancel(senderSNew);
senderSNew.cancel();
where NDX is the same as started. That is 0 in your case. Or, much better, change your NDX to a some random contant number.
to stop:
Intent intent = new Intent(ctx,YourService.class);
intent.addCategory("SOMESTRING_AS_TAG");
ctx.stopService(intent);
I'm using the AlarmManager to fire a notification daily in specific time which is selected via time picker. The notification fired correctly in the same day but doesn't repeat correctly every day!!!
This is the method for setting the notification using setRepeating():
public void witer_reminder(View view)
{
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Witer_Notification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
Calendar calSet = (Calendar) cal.clone();
calSet.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
calSet.set(Calendar.MINUTE, picker.getCurrentMinute());
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(cal) <= 0)
{
// Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
24 * 60 * 60 * 1000, pendingIntent);
}
and this is the BroadcastReciver class:
public class Witer_Notification extends BroadcastReceiver
{
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent)
{
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
PendingIntent actiontIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Suggestion.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("")
.setStyle(new NotificationCompat.BigTextStyle().bigText(""));
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
// mBuilder.setStyle(new NotificationCompat.InboxStyle());
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
BTW, the application target is SDK 19.
I found that the setExact() replacing to set()
Correct.
it's not applicable for intervalAtMilis as a parameter
Not directly. But, when you get control in your BroadcastReceiver from the setExact() event, call setExact() again to schedule the next event.
I didn't find anything for setRepeating()
There is no simple solution, because Google is trying to point out to you that this is bad for the battery. Using setExact() as described above is your only option for exact repeating.
I am working in a Android application in which i want to show alert during shift change,Let say after every 8 hrs. How can I do it?
I have tried a lot, All are working with some major problem. Can i get a tutorial or tip how i can do it. i am giving what i have tried
public class ShiftConfirmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Intent intent1 = new Intent(this, ShiftAlert.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
You can use ALARM MANAGER
Also there are some tutorials on it as follows
1)http://www.techrepublic.com/blog/android-app-builder/use-androids-alarmmanager-to-schedule-an-event/
2)http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
3) You can try this code snippet for test of 24 hrs
Intent myIntent = new Intent(ThisApp.this , myService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent); //set repeating every 24 hours
4)http://learnandroideasily.blogspot.in/2013/05/android-alarm-manager_31.html
5)http://khurramitdeveloper.blogspot.in/2013/06/android-alarm-manager-to-start-service.html
set the following code in the activity where you are starting your service:
Intent myIntent = new Intent(ThisApp.this , myService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 8*60*60*1000 , pendingIntent); //set repeating every 8 hours
One more thing, you need to make a receiver which starts your service if your device is switched off. For that you also need to make few changes in Android manifest file also.
public class MyScheduleReceiver extends BroadcastReceiver {
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 300;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, YourService.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar cal = Calendar.getInstance();
service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 8*60*60*1000, pending);
// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
// REPEAT_TIME, pending);
}
}
Android Manifest File:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.fleetcare.MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You can also use pending intent for particular time.
Intent intent = new Intent(this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
For more Android Notifications - Tutorial
I have this code:
set alarm:
public void setAlarm()
{
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.add (Calendar.DAY_OF_YEAR, 1);
Calendar_Object.set(Calendar.HOUR_OF_DAY, 0);
Calendar_Object.set(Calendar.MINUTE, 0);
Calendar_Object.set(Calendar.SECOND, 1);
Intent myIntent = new Intent(Main.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Main.this,
0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),1000*60*60*24, pendingIntent);
}
Broadcast receiver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, NotificationService.class);
context.startService(myIntent);
}
}
the service:
public class NotificationService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext()
.getSystemService( this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), ABC.class);
Notification notification = new Notification(R.drawable.ic_launcher,
"xxx", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(),
"abc", "xyz",
pendingNotificationIntent);
mManager.notify(0, notification);
}
}
after setting the alarm at 00:00:01 everything is perfect but the next time the problem is happening. the PendingIntent triggers like 6 to 8 times between the 24 hours interval. I don't remember if the time is the same for each trigger but I want it one time each day. What is wrong with the code?
This will create an alarm that will go off every day at 00:05, the important part is the AlarmManager.INTERVAL_DAY
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 5);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.HOUR, 24);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
mgr.cancel(pi);
mgr.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
Also, don't forget to always cancel previous similar alarms, when re-setting a new one, or else they'll all go off, old set alarms, and the new one, see above mgr.cancel(pi);