I want to use a service that run in background indefinitely and call a method every 10 minute
and its running even app killed
How to create it?
You can do by using service as follows
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//performe the deskred task
}
}, 10minutes time in milisecods);
// If we get killed, after returning from here, restart
return START_STICKY;
}
This service will get started automatically even if app get killed, and postdelayed will run
For "how to work with services", see
Services - Android
Services in Android - Vogella
Here is a clear solution that focus on "every 10 minutes" part using AlarmManager: https://stackoverflow.com/a/10222390/2591556
Assuming you have a Running Service
User AlarmManager to run Service every 10 minutes
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, YourService.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 600000, pi); // Millisec * Second * Minute
}
you could write a background Service:
Running in a Background Service
and start the service every 10-11 min (cause of AlarmManager power saving behaviour), or with exact timing (needs to shedule next execution every time) with AlarmManager.setExact
Example:
private static PendingIntent createClockIntent(Context context) {
Intent intent = new Intent(context.getString(R.string.widget_broadcast_clock_update));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
public static void startClockAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
clockIntent = createClockIntent(context);
alarmManager.setRepeating(AlarmManager.RTC, 0,
600000, clockIntent);
}
You can use the Alarm manager which will be called after every 10 mins
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.setClass(this,AlarmReceiver_.class);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(YourClass.this, m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 300000L,
600000L, broadcast);
ManiFest receiver Code where you will get a receiver response
<receiver android:name="com.yourpackage.AlarmReceiver_"
>
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You will have to create Receiver where you will receive data as an above-specified name of AlarmReceiver_.class
Related
im trying to do somekind of auto GoogleDrive backup(uploading a file) timer, but i cant set the specific time, even if i set to 5 seconds(testing purpouse, it just run every 1minute) and when the user reboot the phone, it only RUN one time (the Alarm is not called =/, so the application has to be opened one time after the boot)
Manifest Configuration:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application...>
<receiver
android:name=".Tools.AutoBackupAlarmBroadCast"
android:process=":remote" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".Tools.AutoBackupService"
android:exported="false" />
</application>
and with this WakeBroadCast:
public class AutoBackupBootStarter extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, AutoBackupService.class);
context.startService(startServiceIntent);
}
}
make sure that the AutoBackupAlarm is called on boot, but it only happens ONE time, i need it to start the trigger to repeat by the user setted time(will get it from shared Preferences)
the service:
AutoBackupService:
public class AutoBackupService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
*/
public AutoBackupService() {
super("AutoBackup");
}
#Override
protected void onHandleIntent(Intent intent) {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
//HERE i must start the Async to make the GoogleDrive Backup
//the next doubt will be how can i get sharedpreferences and activity to pass to the async from HERE?
Log.d("BACKUP", "AutoBackupLogTest");
}
}
the broadcast
public class AutoBackupAlarmBroadCast extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AutoBackupService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
the AlarmFunction called on onCreate, that almost works how i want, it cant repeat every 5 seconds like the time below, it only show every 1 minute
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AutoBackupAlarmBroadCast.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, AutoBackupAlarmBroadCast.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
1 * 5 * 1000, pIntent);
}
Try below code to repeat task after particular time interval
boolean alarmUp = (PendingIntent.getBroadcast(this, 444, new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_NO_CREATE) != null);
if(!alarmUp){
AlarmManager alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent DataSyncIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 444, DataSyncIntent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
15 * 60000, // 60000 = 1 minute,
pendingIntent);
}
I was trying to display the notifications using background service for which I wrote 3 classes. The service should run in background even if the appllication closed and and it should start running automatically so I used ,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.s2si.ucom.ui.UcomBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
So in onReceive() of BroadcastReceiver class I am starting the service using,
Intent service = new Intent(context, AlarmService.class);
context.startService(service);
In service class I am using AlarmManager to set particular interval so that I can display notification for every period of time. and finally I am invoking the BroadcastReceiver class to display the notification using AlarmManager. The problem is I am not getting the output :-(...instead of that I am getting error like, Couldn't load memtrack module (No such file or directory)... I am literally new to android coding...Can any one help me how to display notifications in such manner..and let me know what I did wrong above...Thanks much :-).
code in onCreate() method of service class,
Intent intent = new Intent(context, NotificationServiceReceiver.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
// We want the alarm to go off 5 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 5 * 1000;// start 5 seconds after first register.
// Schedule the alarm!
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 5000, sender);// 5seconds interval
in short this is how you create a broadcast
private static final String ACTION_ALARM = "your.company.here.ACTION_ALARM";
public static void createAlarm(){
Intent alarmIntent = new Intent();
alarmIntent.setAction(ACTION_ALARM);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timestamp for alarm, pi);
}
public void onReceive(...){
//whatever is supposed to happen on receive
}
and you need to declare that broadcastreceiver and the actionname its supposed to receive in manifest:
<receiver
android:name="your.company.here.AlarmReciever">
<intent-filter>
<action android:name="your.company.here.ACTION_ALARM" />
</intent-filter>
</receiver>
So I have a BroadcastReceiver which looks like this:
public class UpdateReceiver extends BroadcastReceiver {
public UpdateReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
System.out.println("Broadcast received");
PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), cal.getTimeInMillis(), operation);
}
}
This is how I call the BroadcastReceiver
Intent in = new Intent ("REFRESH_BROADCAST");
sendBroadcast(in);
And this is my intent-filter in Android Manifest file
<service android:name = ".services.RefreshService">
<intent-filter>
<action android:name="REFRESH_THAT"/>
</intent-filter>
</service>
<receiver android:name=".services.UpdateReceiver">
<intent-filter>
<action android:name="REFRESH_BROADCAST"/>
</intent-filter>
</receiver>
BroadcastReceiver received a brodcast without any problem, but AlarmManager seems to do nothing. If I call operation.send() it works without a problem, so I presume there is something wrong with AlarmManager.
Alright so finally I found a solution a it was my fault.
I have set int type to AlarmManager.ELAPSED_REALTIME and long triggerAtMillis to System.currentTimeMillis() property of alarmManager.setInexactRepeating(.....) which is wrong, it only can be paired with AlarmManager.RTC / RTC_WAKEUP.
So the functional code is this:
PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() , 30000, operation);
I should really read API documentation more carefully. If you hover AlarmManager.ELAPSED_REALTIME , it will told you what kind of time trigger you have to use. Hope this my stupid mistake will help someone in future.
As per the setInexactRepeating doc, The third parameter is:
intervalMillis: interval in milliseconds between subsequent repeats of the alarm
Then you should put 10000 ms (which is 10 sec) instead of cal.getTimeInMillis()
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, cal.currentTimeMillis(), 10000, operation);
Which means that, youer alarm will go off after 10 sec of the intent firing, then will repeat each 10 sec. And of course, since you are using this method, This is inexact timing.
In the below code, it is doing the main thing what I want so far:
- Repeats every hour at the same time
Can someone verify if or what I need to do to make sure of the following items?
(1) The alarm will eventually be based on days of a month. As long as it goes off when they wake their phone up (to save battery). It is not hour or minute specific. Only day. How can this be achieved?
(2) If the Activity is destroyed or the phone is rebooted, I am not sure if my AlarmManager stays awake?
(3) Lastly, This code is repeated every time the app starts (thus overwriting any existing AlarmManagers; is this a proper way of doing things, or should I be checking to see if an Alarm exists?
for (int i : AlarmDays) {
if (String.valueOf(i) == null ) {
continue;
}
Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.MINUTE) >= i)
cal.add(Calendar.HOUR, 1);
cal.set(Calendar.MINUTE, i);
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60 * 60 * 1000, pendingIntent);
}
// TimeAlarm.class
public void onReceive(Context context, Intent intent) {
String DebtName = null;
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Payment Due";
CharSequence message = "Open App and Update your Balance";
Intent notificationIntent = new Intent(context, ManageDebts.class);
notificationIntent.getExtras();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Notification notif = new Notification(R.drawable.icon, "Pay "
+ DebtName + " today!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.defaults = Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS;
nm.notify(1, notif);
}
And in my application tag in my manifest:
EDIT:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<Application>
<receiver
android:name=".TimeAlarm"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</Application>
The AlarmManager will not persist across the phone being rebooted. However, it will persist across the application being killed by the Android scheduler. Because of this, you basically need to:
Store your schedule somewhere, and come up with a scheduling algorithm for deciding the next time you want an AlarmManager to fire.
Each time you get an alarm, schedule a new one.
Start the AlarmManager on boot, by catching the BOOT_COMPLETED broadcast.
I have a boot_completed receiver which gets notified on boot.
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
But it appears to get called multiple times. I start a timer, and then a service, which leads to multiple timers, and then the service gets reset and runs again.
Creating timer like this. This is not a repeating timer, is it?:
private void setAlarm(Context context, long interval) {
try {
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(RespondAlarmReceiver.ACTION_RESPOND_SMS);
intent.putExtra("isChecking", true);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long triggerAtTime = SystemClock.elapsedRealtime() + interval; //interval is 60,000
alarms.set(alarmType, triggerAtTime, alarmIntent);
}
catch (Exception e) {
Log.e(DEBUG_TAG, "Unable to set alarm");
}
As a side note, if anybody knows how to attach the Eclipse debugger to the Boot-up broadcast receiver or to a running service, that would be fantastic.
It's strange that you'd be getting multiple timers started. Try passing PendingIntent.FLAG_ONE_SHOT as the last argument inside of PendingIntent.getBroadcast