I want to show my problem by an example:
I set a RTC_wakeup repeating to 10am that triggers an IntentService, When I run my application in 9:30am it waits until 10am and triggers the service (Great!).
But when I run my application at 10:30, It determines that the scheduled time has passed so it triggers the service (not what i want).
I just want my service to be triggered every day just once, exactly at 10am, what should I do? (The problem is whenever application runs after 10am it triggers the service)
here is my code:
public class AlarmReceiver extends WakefulBroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, ServiceFTP_LogFileUpload.class);
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, service);
}
public void setAlarm(Context context) {
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 10:00 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}
public void cancelAlarm(Context context) {
// If the alarm has been set, cancel it.
if (alarmMgr!= null) {
alarmMgr.cancel(alarmIntent);
}
}
}
And the alarm is set in SplashScreen (Launcher activity):
AlarmReceiver alarm = new AlarmReceiver();
alarm.setAlarm(this);
Related
I would create an alarm clock, I wrote this code but return this error:
2019-02-05 10:58:13.902 2663-10077/com.google.android.gms E/ChromeSync: [Sync,SyncIntentOperation] Error handling the intent:
Intent { act=android.intent.action.PACKAGE_ADDED
dat=package:com.example.iacopo.alarmgroup flg=0x4000010
cmp=com.google.android.gms/.chimera.GmsIntentOperationService (has
extras) }.
How can I fix it? Thanks. And this code doesn't create an icon of alarm in the notification panel, near the clock.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.clear();
cal.set(2018,1,5,10,0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
this.startService(intent);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
}
and the receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("test","ok");
}
}
cal.set(2018,1,5,10,0);
The calendar takes earlier than the current time, so your alarm clock is unlikely to be triggered. Change the time correctly and try again.
This is a basic snippet from developer.android.com. You can change date and time as per your needs and pass the calendar instance to Alarm Manager intent.
// Example: Wake up the device to fire a one-time (non-repeating) alarm in one minute:
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);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
60 * 1000, alarmIntent);
// Example: Set the alarm to start at approximately 2:00 p.m. say
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// 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);
I am busy with a daily quote app... Alarm Manager is set up to run a method in the MainActivity that populates a listView with a quote from the database each morning at 0900. The method runs and the listView populates just fine but ignores the alarm schedule and the populated data doesn't persist.
If users leaves the main activity then returns, or closes and reopens the app, the method is run again and the list view is populated with a new quote rather than persisting and only running at the scheduled interval.
Any ideas on how to fix this?
Here is my code:
Here I register the alarm dynamically in the MainActivity's onCreate method:
mTodaysQuoteReceiverStaticInnerClass = new
TodaysQuoteReceiverInnerStaticClass();
IntentFilter filter = new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
this.registerReceiver(mTodaysQuoteReceiverStaticInnerClass, filter);
Here is my receiver class (which I made an inner class in the MainActivity):
public class TodaysQuoteReceiverInnerStaticClass extends BroadcastReceiver{
#Override
public void onReceive(final Context context, final Intent intent){
MainActivity.this.PopulateTodaysQuote();
}
}
Here is the method that sets my alarm. I call this method from the onCreateMethod in the MainActivity:
public void todaysQuoteAlarm(){
long currentTime = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 9);
calendar.set(Calendar.SECOND, 0);
if (currentTime <= calendar.getTimeInMillis()) {
Intent myIntent = new Intent(this,
TodaysQuoteReceiverInnerStaticClass.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)
this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
else{
I am making a notification application and for that i am using scheduled alarms for running the notifications using Broadcast receiver class and i am prompting user to select from daily or hourly notifications and i am defining both alarms in the same receiver under the same function and it is working fine but the problems comes when i restart my device,when i restart it both the alarms (daily and hourly) are getting triggered when i am only setting one for example if i set an alarm for 11:20 A.M and restart my device the hourly one and this 11:20 one both are getting triggered,i want that when i restart my device only the alarm which was selected before the device boot only gets triggered.
My receiver class:-
public class alarmreceiver extends BroadcastReceiver {
int id=0;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm running", Toast.LENGTH_SHORT).show();
start(context,id);
}
static void start(Context context,int id) {
Intent intent = new Intent(context, notification_receiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (id==1) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 11);
calendar.set(Calendar.MINUTE, 9);
calendar.set(Calendar.AM_PM, Calendar.AM);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingintent);
}
else
if (id==2) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 60 * 1000
, pendingintent);
}
}
I am calling this function under button click listener like this:-
For daily notifications:-
alarmreceiver.start(getApplicationContext(),1);
For hourly notifications:-
alarmreceiver.start(getApplicationContext(),2);
This code:
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 60 * 1000, pendingintent);
sets a repeating alarm that goes off every minute, not every hour!
Also, this code sets an alarm that goes off right now and again every minute. The second argument to setRepeating() is the time of first alarm. You've passed SystemClock.elapsedRealtime() which basically means "now".
I'm failing to see why this alarm is going off on a reboot...I am setting it 7 days ahead here -
Intent intent = new Intent(MainActivity.this, Reminder.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MainActivity.this, 1, intent, 1);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
try {
am.cancel(pendingIntent);
} catch (Exception e) {
System.out.println("Derp");
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 7);
long time = calendar.getTimeInMillis();
am.set(AlarmManager.RTC_WAKEUP, time,
pendingIntent);
Here is my manifest that I have set for alarm to stick around on a reboot - Reminder is the class receiving the alarm-
<receiver android:name="com.practicum.notifications.Reminder" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
By default, all alarms are canceled when a device shuts down. To prevent this from happening, you can design your application to automatically restart a repeating alarm if the user reboots the device. This ensures that the AlarmManager will continue doing its task without the user needing to manually restart the alarm.
You have to manually reset the alarm once again in Bootup Receiver
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Set the alarm here.
}
}
All alarms are shut off when you power off the Android device.
You need to call setRepeating method
public class AlarmReceiver extends BroadcastReceiver {
private static final int PERIOD=5000;
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
static void scheduleAlarms(Context ctxt) {
AlarmManager am = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, YourService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
}
Check this answer from CommonsWare.
For future reference, I misunderstood how receving the boot complete action worked. I had the intent filter in both of my receiver classes so they were both running, when instead I needed an intent filter on a new broadcastreceiver class to RESET my alarmmanagers.
Have a BroadcastReceiver which I want to create a PendingIntent inside the onReceive method
public class MyPushNotificationReceiver extends BroadcastReceiver {
..
public void onReceive(Context context, Intent intent) {
// How to start a PendingIntent here?
}
Most of the doc from Google is not starting within the onReceive method, so any sample cod e I can use?
Thanks.
a sample code which uses a pending intent in broadcast reciver pls check
public class MyScheduleReceiver extends BroadcastReceiver {
// Restart service every 30 minute
private static final long REPEAT_TIME = 1000 * 30 ;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
//
// Fetch every 30 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
// REPEAT_TIME, pending);
}
}
this code is from vogella ...