How to stop service at particular time on Android? - android

Start my service at : 8am. I don't know how to stop service at specific time.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this,
(int) System.currentTimeMillis(), intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pi);
I want Myservice start at 8am and stop at 6pm in everyday.
Please help me. Thanks.

you could use the AlarmManager, .cancel(PendingIntent intent) at the myService.class, checking whether it's 6pm and cancel the alarm if the intent exists.
Check the API:
Alarm Manager API

This might be an old question but I came across this issue myself today and figured a way to do it:
You can use a new service which stops your service, and start that service in the desired time on a daily basis using alarm manager, like this:
Define the service which will stop your service:
package com.youractivity;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyServiceTerminator extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
public void onCreate()
{
Intent service = new Intent(this, MyService.class);
stopService(service); //stop MyService
stopSelf(); //stop MyServiceTerminator so that it doesn't keep running uselessly
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
add the following code after the one you posted, and run the method inside your activity:
private void stopRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getTimeZone("GMT+3"));
updateTime.set(Calendar.HOUR_OF_DAY, 18);
updateTime.set(Calendar.MINUTE, 0);
Intent intent = new Intent(this, MyServiceTerminator.class);
PendingIntent pintent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);
}
this way the service will be scheduled to start as you posted above, and scheduled to stop at 6 as shown in the code I posted.

You can use AlarmManager for scheduling and cancel method to stop.
alarmMgr.cancel(alarmIntent);
you can find all your necessary information here
https://developer.android.com/training/scheduling/alarms.html

Related

Alarm Manager is not working in Android

I need to setup an Alarm in some interval of times. To achieve it I wrote:
TestFragment class
private void setupAlarmManager(){
AlarmManager manager = manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(getContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i, alarmIntent, PendingIntent.FLAG_ONE_SHOT);
manager.set(AlarmManager.RTC_WAKEUP,1499510100000L, pendingIntent);
manager.set(AlarmManager.RTC_WAKEUP,1499510220000L, pendingIntent);
}
AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
I put the debug point at Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show(); but nothing happened.
4PM = 1499510100000L
4:03PM = 1499510220000L
What Am I doing wrong here? Further I want to add a Local notification in onReceive method.
You should use a Calendar object to set up the alarm time.
For an alarm at 4PM you could do something like:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);
Then you set up your AlarmManager as you already did but for the last line use:
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Maybe you want to use a repeating Alarm or even a Handler
If so you should visit: https://developer.android.com/training/scheduling/alarms.html

alarm not triggering when app is no running

I'm setting up a daily alarm. It works if the app is running at alarm time, but does not work if the app is not running.
This is how I declare the receiver in the Manifest:
<receiver android:name="com.myAppPackage.alarm.AlarmReceiver"
android:enabled="true"
android:exported="true"/>
Studio warns me: Exported receiver does not require permission.
True I have not added an android:permission nor and Intent to the receiver and the application section doesn't have any permission tags.
And this is the broadcastreceiver:
package com.myAppPackage.alarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver(){}
#Override
public void onReceive(Context context, Intent intent) {
final Intent syncIntent = new Intent(context, AlarmActivity.class);
syncIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(syncIntent);
}
}
The alarm is configured in the following method (in this example configured to set-off daily inexact at 13:48):
public static void configureDailySync(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
final int hourOfDay = 13;
final int minuteOfHour = 48;
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minuteOfHour);
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
alarmPendingIntent);
}
Any help is very welcome! Thank you!!
news: getting closer... if I copy the alarm-setting code in the MainActivity onCreate() method it works! This is the code I copied:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
final int hourOfDay = 13;
final int minuteOfHour = 48;
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minuteOfHour);
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
alarmPendingIntent);
When the alarm is created as above in the onCreate() of the MainActivity then it DOES trigger even when the app is closed...
But when I call the call the method from the MainActivity like this:
MyAppAccount.configureDailySync(this);
it doesn't work!
MyAppAccount is an plain class not extending anything... I've tried to have MyAppAccount extend AppCompatActivity in case it mattered but nothing...
Oh well... it seems that the above try of executing the alarm-setting in the onCreate() method of the MainActivity is not always working... what is most puzzling!!! :-(
SOLVED: It had nothing to do with coding!! The problem was the way I was closing the application. When closing the application using the stop button of Android Studio the alarm is NOT set. When closing the application from the phone, using the back button for instance and / or removing the application from the list of applications (with the square button), then the alarm works!
Why? No idea...

AlarmManager and Service - Starting several services?

I want to accomplish to spawn a service every hour. This service should perform some SQL database operations. In order to do so, I've used AlarmManager like this:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Home.this, DeleteCaseService.class);
PendingIntent pintent = PendingIntent.getService(Home.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*60*1000, pintent);
I haven't made the code for the service yet, but that's not the problem. My problem is kinda theoretical. If you imagine this app running for 8 hours constantly, will there will be started 8 different Service in 8 different threads? Or when will a service get killed? Is this the best approach? Feel free to suggest other solutions, but I want to keep the AlarmManager
Thanks.
Instead of using service use broadcast receiver for making background operation on database
to call the broadcast receiver use the bellow code
public class AlarmMgnr
{
private Intent intent;
Context context;
private static AlarmManager aMgnr;
private static PendingIntent sender;
public AlarmMgnr(Context context)
{
this.context = context;
}
public void registerAlarm()
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
System.out.println("AlarmMgnr.registerAlarm()");
intent = new Intent(context, <YourReciverCalssName>.class);
sender = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
aMgnr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, sender);
aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 180000L, sender);
// aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60000L, sender);
}
public void unregisterAlarm()
{
aMgnr.cancel(sender);
}
}
}
And start this alaram manage once only when application got installed .

In android, is it possible to use more than one AlarmManager with different repeat values in a single application?

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" />

Android AlarmManager Constantly goes off

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?

Categories

Resources