Hello i want to make a background service to update the data of my app and repeat it once a day, also i want the service to start onboot. I have the following code:
public class OnBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Create Intent
context.startService(new Intent(context, BackgroundServiceHandler.class));
}
}
I have a settings menu so the user can choose the hour of the repeating alarm.
How can i reset the time of the alarmmanager? Where i have to put the code of the alarm manager? Do i have to use service or intentservice? How to check if service is running?
Alarm manager code:
Intent intent = new Intent(MainActivity.this, AlarmService.class);
intent.putExtra("i", 3);
PendingIntent pi = PendingIntent.getService(MainActivity.this, 9, intent, 0);
// every day at 9 am
Calendar calendar = Calendar.getInstance();
// if it's after or equal 9 am schedule for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
}
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
How can i reset the time of the alarmmanager?
How to edit/reset Alarm Manager?
Where i have to put the code of the alarm manager?
For example you can place that code in static method and call it from place where user set time and from OnBootReceiver. How to implement class which will receive event OnBoot please check that answer.
Do i have to use service or intentservice?
Service vs IntentService
How to check if service is running?
Check if service is running on Android?
Related
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 trying to update fragment on clock time, say for example 8PM, with below logic. Unfortunately, it doesn't update the fragment. Any help/reference would be appreciated.
What I did:
registered an AlarmManager in app's Application class as below:
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent().setAction(AppConstants.INTENT_ACTION_UPDATE_DASHBOARD);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at Consulting start time
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
Listens for AlarmManager in Fragment as below:
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mDashboardUpdateReceiver, new IntentFilter
(AppConstants.INTENT_ACTION_UPDATE_DASHBOARD));
and performs actions if broadcast receives:
private BroadcastReceiver mDashboardUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Dashboard updating...");
updateCounters();
}
First, a PendingIntent does not trigger a local broadcast. You cannot use LocalBroadcastManager here.
Second, using AlarmManager to update a UI is rather odd. If your UI exists, you have a process running, so you could use something in-process (e.g., ScheduledExecutorService) rather than fussing with AlarmManager.
Third, you are not taking into account that set(Calendar.HOUR_OF_DAY, hour) and calendar.set(Calendar.MINUTE, minute) might change the Calendar to be in the past. Imagine if you execute your first code snippet at 23:00, with hour set to be 22 and minute set to be 0. The Calendar object that you create will be for today, but for 22:00 today, which was an hour before now (23:00). You need to check the Calendar, see if it is in the past, and if so, add() a day or otherwise adjust it to some future time.
in my task application, i want to create alarm service for multiple items. Here is the code i followed to create service. Lets assume, if there are more than 5 items present in list. then we will sent alarm service for 5 different times.
What if the user comes and edits the time?, how to update the system and make sure it triggers at new instance?. What if the user delete the task, how to quickly removes the registered alram for the deleted task?
What about uninstalling the app?, how to clear all the entries?, what if the system re-boots?
This is the code i'm following to register the task in alram services
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.MONTH, 8);
Calendar_Object.set(Calendar.YEAR, 2012);
Calendar_Object.set(Calendar.DAY_OF_MONTH, 6);
Calendar_Object.set(Calendar.HOUR_OF_DAY, 14);
Calendar_Object.set(Calendar.MINUTE, 25);
Calendar_Object.set(Calendar.SECOND, 0);
Step 2:
We need to create an alarm which help us to invoke the BroadCastReceiver on our specified time.
// MyView is my current Activity, and AlarmReceiver is the BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MyView.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
The following sets the Alarm in the specific time by getting the long value of the alarm date time which is in calendar object by calling the getTimeInMillis(). Since Alarm supports only long value , we're using this method.
*/
alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),
pendingIntent);
Use this method to set Alarm :
public static void startAlarm(Context context, int alarm_code, String time) {
String[] arrTime = time.split(":");
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
PendingIntent mAlarmSender = PendingIntent.getBroadcast(context,
alarm_code, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeZone(TimeZone.getDefault());
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arrTime[0]));
cal_alarm.set(Calendar.MINUTE, Integer.parseInt(arrTime[1]));
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, mAlarmSender);
}
Here,"int alarm_code" is your unique code for particular item.
And for update alarm first cancel the existing alarm and set new alarm for new time.For that use this method :
public static void cancelAlarm(Context context, int alarm_code) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
am.cancel(PendingIntent.getBroadcast(context, alarm_code, intent, 0));
}
Here,"int alarm_code" will be your unique code which you have used to set alarm.So that alarm with particular alarm_id will be cancel.You can also delete alarm with this method.
Same way you can clear all the alarms passing alarm_code to the given function.
You have to register receiver for system reboot and in onReceive of register you have to set all alarms again.
Hope this will help you.
I'm developing an application for mobile and tablet using android 2.3**
I want to do some operations namely Operation-A and Operation-B. Both perform some pocess.
I want to repeat the Operation-A and Operation-B is performed every 1 hour time interval
Operation-A is performed before the 10 minutes of Operation-B
Operation-B is performed when the time is 0.00,1.00,2.00,3.00,....,23.00 (I'm using railway time. So it is not confused for am or pm).
Operation-A is performed when the time is 0.50,1.50,2.50,3.50,....,23.50
The above scenarios is possible in android or not.
All are give your ideas for the above scenarios.
I'm planning to use AlarmManager. AlarmManager is android system service. It is used to notify the application every 1 hour.
I plan to use an AlarmManager for Operation-A and another AlarmManager for Operation-B.
My doubt is ,In android is it possible to use more than one AlarmManager with different repeat values in a single application?
All your ideas are welcome.
Yes this task will done with help of AlarmManager with reperating functionality. First you need to create two receiver class which will receive events . and then need to setup repeating alarm .
private void setAlarm1()
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.HOUR, 1);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60, pendingIntent);
}
private void setAlarm2()
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 50);
Intent intent = new Intent(this, AlarmReceiver_1.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*50, pendingIntent);
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
public class AlarmReceiver_1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
In menifest, you need to declare the classes as below.
<receiver android:name=".AlarmReceiver" />
<receiver android:name=".AlarmReceiver_1" />
I am using AlarmManager for my Timer. I have 2 classes.
In the first class (MainActivity) I am starting my alarm with the next code:
public void startAlarm(long Seconds) {
Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 13141337,
myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, (int) Seconds);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
}
In another class (AlarmSound), where the alarm goes off and the phone vibrates, I'm calling my cancel Alarm method.
public void stopAlarm(){
Intent intentstop = new Intent(AlarmSound.this, MyAlarmService.class);
PendingIntent senderstop = PendingIntent.getBroadcast(AlarmSound.this,
13141337, intentstop, 0);
AlarmManager myalarm = (AlarmManager) getSystemService(ALARM_SERVICE);
myalarm.cancel(senderstop);
Log.w("Karl","stopAlarm?");
}
Is this the correct way to do this? Because my alarm constantly goes off on android 4.1.
Thanks in advance!
Your Cancel wont work. The pending Intents have to match - since they have a different context (MainActivity and AlarmSound) this cancel wont work. You have to also use getService on both.
You can
a) try to recreate a matching pending Intent
b) get the pendingIntent that started the Service in the Service and use that to cancel
But usually every Alarm just goes off once if you dont use setRepeating().
Are you sure you are terminating your Service correctly with stopself() and are giving it the right flag in the onStartCommand() Method?