AlarmManager.setRepeating - Service does not seem to repeat - android

I'm working on an Android app that sues a background task to fetch XML from a URL every x seconds (user defined interval, defaulting to 60). My structure is as so:
MainActivity
This schedules an Alarm via AlarmManager:
public static void scheduleAlarm(Context voContext, int viCheckInterval)
{
try {
moAlarmManager = (AlarmManager) voContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(voContext, AlarmReceiver.class);
moAlarmIntent = PendingIntent.getBroadcast(voContext, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, viCheckInterval);
moAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
time.getTimeInMillis(), moAlarmIntent);
} catch (Exception e) {
Log.e("MessageCheckAlarmHandler", e.toString());
}
}
AlarmReceiver
This is a BroadcastReceiver that starts the service:
#Override
public void onReceive(Context context, Intent intent)
{
Context oAppContext = context.getApplicationContext();
if (oAppContext == null) {
oAppContext = context;
}
Intent serviceIntent = new Intent(oAppContext, MessagingService.class);
oAppContext.startService(serviceIntent);
}
MessagingService
This creates our in-house logger (logging over TCP) and starts an AsyncTask called FetchPageTask:
public class MessagingService extends Service
{
#Override
public void onCreate()
{
super.onCreate();
...
this.acquireLocks();
try {
String sCheckerUrl = oPreferences.getString("pref_server", "");
int sCheckerPort = Integer.parseInt(oPreferences.getString("pref_server_port",
"8050"));
sCheckerUrl = String.format(URL, sCheckerUrl, sCheckerPort);
this.moFetchInboxTask = new FetchPageTask(this.logger, this);
this.moFetchInboxTask.execute(sCheckerUrl);
} finally {
this.releaseLocks();
this.stopSelf();
}
}
#Override
public void onDestroy()
{
super.onDestroy();
this.logger.close();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
/**
* Acquire a WakeLock and a WifiLock.
*/
private void acquireLocks()
{
try {
// Acquire a wake lock to prevent the device from entering "deep sleep"
PowerManager oPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
this.moWakeLock = oPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
this.moWakeLock.acquire();
// Acquire a WiFi lock to ensure WiFi is enabled
WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
this.moWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
this.moWifiLock.acquire();
} catch (Exception e) {
this.logger.error(TAG + "->onCreate()", "Error acquiring locks: " + e.toString());
}
}
/**
* Release our WakeLock and WifiLock.
*/
private void releaseLocks()
{
try {
this.moWakeLock.release();
this.moWifiLock.release();
} catch (Exception e) {
this.logger.error(TAG + "->releaseLocks()", e.toString());
}
}
}
FetchPageTask
This extends AsyncTask and does all the work of fetching the page and parsing the XML. It also then adds notifications and performs actions on the data retreived if need be.
This all works fine once, but does not run subsequently. I know that the AsyncTask works as I was previously doing it using pure Java via ScheduledExecutorService and ScheduledFuture and it worked. The only reason I decided to change to using AlarmManager is for maintainability purposes.

First, you are setting up your alarm to occur immediately, and then every ~43 years thereafter. That is unlikely to be what you want. Modify the third parameter of your call to setRepeating() to be the desired period in milliseconds, which right now is set to the number of milliseconds since midnight 1 January 1970.
Second, you are acquiring your WakeLock too late. There is no guarantee that your acquireLocks() will get a chance to run before the device falls asleep. My WakefulIntentService or the new WakefulBroadcastReceiver offer better patterns for passing control to an IntentService.

I think you don't need the Calendar here. You just want to run the action every x seconds, so It would be something like this:
moAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
viCheckInterval, moAlarmIntent);
// viCheckInterval should be long miliseconds

Related

Callback listener when application is killed from recent applications in android

Let me come straight to my issue.
There is an old similar question:
Continue Service even if application is cleared from Recent app. Please go through the link before going ahead.
I have to save some data to the local database before the application is destroyed completely.
I have following issues with onTaskRemoved() method of the service:
onTaskRemoved() method is not triggered every time the application(and hence the service) is stopped from the recent applications screen.
Even if onTaskRemoved() is called every time, the method is not executed completely. I mean if there are 20 statements in the method, only 5 or 10 statements are executed and the method breaks after that. Like if I have 20 System.out.println() statements than only 5 or 10 or 12(any random number) statement prints and method breaks after that.
So I can rely on the method onTaskRemoved() method for cleaning up resources acquired by the application.
This is a blocking issue for my application release. I have tried every trick. Like having at least one activity in the stack(I am calling it GhostActivity) so that if the application is killed from the recent applications screen, we can do clean up in onDestroyed() method the activity. onDestroyed() is called but it has exact same issues like onTaskRemoved() method.
I am stuck on the issue since weeks and it's very annoying. Please let me know if anyone has any solution.
I finally myself got it worked. I used a combination of service and alarm manager. Every-time I want to handle the force close scenario, I start a service in which I run an infinite loop. This loop will iterator every 15 secs. In the loop, I set an alarm 20 secs from the current time. Now if the next iteration of the loop happens the alarm is updated and reset to 20 secs after new current time. In this way, the alarm will trigger only if the service was not destroyed by the user by calling stopService() method.
public class MyIntentService extends IntentService {
public MyIntentService() {
super("My IntentService");
}
private boolean stopped = false;
private Thread runningThread;
private static MyIntentService mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = MyIntentService.this;
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
stopped = false;
runningThread = Thread.currentThread();
while(!this.stopped) {
Intent intent = new Intent("Your_Custom_Broadcast_Action");
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
}
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
mInstance = null;
if (runningThread != null) {
runningThread.interrupt();
}
}
public void stopService() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(broadcastIntent);
stopped = true;
if (runningThread != null)
runningThread.interrupt();
}
public static MyIntentService getActiveInstance() {
return mInstance;
}
}

Improve BroadcastReceiver + AlarmManager

I am experiencing some lag/black screen in my application since I start using AlarmManager + BroadcastReceiver. I have 2 BroadcastReceivers, one to when the phone gets restarted and another that AlarmManager call in the given period of time to send data to the server.
This is the code for BootReceiver to start the alarmManager once the cellphone is rebooted (it is working so far):
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// when the boot is completed, restart the alarm manager
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
SharedPreferences mPrefs = context.getSharedPreferences("GPS_TRACKING", Context.MODE_PRIVATE);
if (mPrefs.getBoolean("hasGeolocation", false) &&
!mPrefs.getBoolean("isThreadOn", false)){
EngineerTracker tracker = new EngineerTracker(context);
try {
tracker.startEngineerTrackingLocation();
} catch (ApplicationException e) {
e.printStackTrace();
}
}
}
}
The method to start and stop the alarm manager is this:
public void startEngineerTrackingLocation() throws ApplicationException{
PendingIntent pendingIntent = null;
AlarmManager manager = null;
ProjectGeospatialConfig geospatialConfig;
// check if the intent is running, if it is not, start it
if (PendingIntent.getBroadcast(context, 0,
new Intent(context, EngineerGeospatialTrackingReceiver.class),
PendingIntent.FLAG_NO_CREATE) == null){
// fetch the geospatial configuration, it may come null, so verify before using
geospatialConfig = getFirstFoundGeospatialConfiguration();
// if not null and use gps
if (geospatialConfig != null && geospatialConfig.isUseGps()){
// session information
SessionInformationDTO sessionInformation = dao.getObjectForKey(SqlLiteStorageKey.USER_INFORMATION);
Integer currentResourceId = sessionInformation.getSecurityHandler().getCurrentUser().getId();
// Retrieve a PendingIntent that will perform a broadcast and add resource id as extra
Intent alarmIntent = new Intent(context, EngineerGeospatialTrackingReceiver.class);
alarmIntent.putExtra("resourceId", currentResourceId.toString());
// set pending intent
if (pendingIntent == null){
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
}
// set manager
if (manager == null){
manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}
// set interval between alarms
int interval = (geospatialConfig.getGpsTrackingInterval() *1000) * 60;
// set alarm repetition
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
interval, pendingIntent);
// set variables for gps tracking
SharedPreferences mPrefs = getApplicationContext().getSharedPreferences("GPS_TRACKING", Context.MODE_PRIVATE);
Editor editor = mPrefs.edit();
// these variables will be measured once db is set
editor.putBoolean("hasExecuted", false);
editor.commit();
}
}
}
both are also working so far, the flag is meant to know when the service has been executed once and will not attempt again at the basic activity (template for all activitied)
The broadcast that is invoked in the alarm manager to send the information in the defined interval is this:
public class EngineerGeospatialTrackingReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String resourceId = intent.getStringExtra("id");
sendLocation(context, resourceId);
}
private void sendLocation(final Context context, final String resourceId){
new RemoteRequestTask<Void>(null, false, null) {
#Override
public Void executeTask() throws ApplicationException {
// working code
}
#Override
public void completed(Void refreshed) {
}
#Override
public void onException(final ApplicationException ex) {
}
}.start();
}}
Both receivers were added to the AndroidManifest. Beside the slowness, i also get a black screen when transitioning from an activity to another.
Use Traceview to determine where you are spending your time, and consider enabling StrictMode to point out where you are doing unfortunate things on the main application thread.
You want onReceive() to be very quick, ideally under 1ms, as. However, it looks like you might be doing database I/O in there (e.g., references to dao), which means that work should be handled off the main application thread, perhaps by an IntentService that you start from onReceive().

Android, getting strength signal (PhoneStateListener) while device in sleep mode

I have problem and after some search I have not found any positive solutions.
After research I have idea that there is not implementation for my problem but this question may be is my last chance.
What do I need to get?
There is application that gets information about mobile network strength signal. I do it by
PhoneStateListener. Of course it works great but when my device goes to sleep mode, listener does not work:
https://code.google.com/p/android/issues/detail?id=10931
https://code.google.com/p/android/issues/detail?id=7592
WakeLock solves problem only in case, if device switch off by timeout. In case when I press hard power button, my device gets sleep mode as well. We can not override power button action.
My goal is get strength signal always when my device is enabled. It does not matter what mode is. All time it should collecting data.
Question:
Are there any ideas? How to achieve that? Are there ways to do this or may be there are some hacks? All solves are welcome. If you had some useful experience, please share this.
Thanks to all for help!!! I hope, this topic will get complete information about this problem.
Alarm manager is the way to go - the tricky part is to keep the phone awake after the alarm manager receiver returns. So
setup an alarm (notice you should also register an "On Boot completed" receiver to set up the alarm after a reboot - your alarms do not survive a reboot) :
Intent monitoringIntent = new Intent(context, YourReceiver.class);
monitoringIntent.setAction("your action");
PendingIntent pi = PendingIntent.getBroadcast(context, NOT_USED,
monitoringIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
// here is the alarm set up
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + INITIAL_DELAY,
INTERVAL_BETWEEN_ALARMS, pi);
receive it - the receiver holds a WakeLock in its onReceive() which never fails :
public abstract class YourReceiver extends BroadcastReceiver {
#Override
final public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if ("your action".equals(action)) {
// monitoring - got broadcast from ALARM
try {
d("SS : " + new Signal().getSignalStrength(context));
} catch (InterruptedException e) {
e.printStackTrace();
}
// Actu8ally the lines above will ANR
// I did it with WakefulIntentService :
// WakefulIntentService.sendWakefulWork(
// context, YourWakefulService.class);
// Will be posting it asap
} else {
w("Received bogus intent : " + intent);
return;
}
}
}
If you are lucky (yourRetrieveSignal() is fast enough) this will work, otherwise you will need a (Wakeful)IntentService pattern in your receiver.
The WakefulIntentService will take care of the wake lock (if you want to avoid a dependency have a look here) - EDIT : keep in mind you can't define listeners in an intent service - see here.
If the receiver ANRs on you, you have to try the WakefulIntentService pattern. In either case you might use this :
This proved the most difficult part actually :
class Signal {
static volatile CountDownLatch latch; //volatile is an overkill quite probably
static int asu;
private final static String TAG = Signal.class.getName();
int getSignalStrength(Context ctx) throws InterruptedException {
Intent i = new Intent(TAG + ".SIGNAL_ACTION", Uri.EMPTY, ctx,
SignalListenerService.class);
latch = new CountDownLatch(1);
asu = -1;
ctx.startService(i);
Log.d(TAG, "I wait");
latch.await();
ctx.stopService(i);
return asu;
}
}
where :
public class SignalListenerService extends Service {
private TelephonyManager Tel;
private SignalListener listener;
private final static String TAG = SignalListenerService.class.getName();
private static class SignalListener extends PhoneStateListener {
private volatile CountDownLatch latch;
private SignalListener(CountDownLatch la) {
Log.w(this.getClass().getName(), "CSTOR");
this.latch = la;
}
#Override
public void onSignalStrengthChanged(int asu) {
Signal.asu = asu;
latch.countDown();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "Received : " + intent.getAction());
Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
listener = new SignalListener(Signal.latch);
#SuppressWarnings("deprecation")
final int listenSs = PhoneStateListener.LISTEN_SIGNAL_STRENGTH;
Tel.listen(listener, listenSs);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.w(TAG, "onDestroy");
Tel.listen(listener, PhoneStateListener.LISTEN_NONE);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is working code (but not the pinnacle of elegance admittedly - comments/corrections welcome). Do not forget to register your services in the manifest and acquire permissions.
EDIT 2013.07.23 : I did not use the onReceive - if you use it it will ANR - this is working code if you use a WakefulIntentService in onReceive and in there you call SignalListenerService.
From my understanding of PhoneStateListener you can't do this while the application CPU is in sleep mode. You can either keep the device awake, which would ruin battery life. Alternatively you can use an alarm (see AlarmManager) to wake the device on intervals, so you can collect the data (impacts battery life still).
Some samples of using AlarmManager can be found here
CommonsWare's location polling example is really good about waking the phone and putting it to sleep again. I think it might help have a look: https://github.com/commonsguy/cwac-locpoll
One of the possible workarounds of android issue 10931 is to send the android.intent.action.SCREEN_ON intent to the 'phone' process after the screen turned off.
Create and register BroadcastReceiver to listen for notifications when the screen turns off
start(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
context.registerReceiver(mScreenReceiver, filter);
}
final BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
Log.v(LOGTAG, "Screen is off. Running workaround");
new Thread(mReportScreenIsOnRunnable).start();
}
}
};
Send the SCREEN_ON intent to the phone process only.
public final Runnable mReportScreenIsOnRunnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Runtime.getRuntime().exec(new String[] { "su", "-c",
"am broadcast -a android.intent.action.SCREEN_ON com.android.phone" });
} catch (IOException e) {
e.printStackTrace();
}
}
};
After receiving this intent the phone process would resume sending cell location
updates.
Root privileges are required.
This solution is a bit hacky, dangerous and works not on all phones. It can lead to higher power consumption, but not so much more than if you keep the screen turned on.

Timeout in BroadcastReceivers using IntentServices

I've got two services running. They do their work and then reschedule themselves via the AlarmManager. In the BroadcastReceiver the only thing that happens is the launching of the service via Context.startService(). Both services are IntentServices, which as far as I can tell shouldn't be causing timeout problems. I've tried IntentServices, threading, and AsyncTasks but am repeatedly bumping up against the timeout error in the receivers themselves.
The timeout message is:
01-18 11:29:04.200: WARN/ActivityManager(73): Timeout of broadcast BroadcastRecord{433a4168 my.package.action.a} - receiver=android.os.BinderProxy#43399978
01-18 11:29:04.210: WARN/ActivityManager(73): Receiver during timeout: ResolveInfo{43394a30 my.package.MyReceiverA p=0 o=0 m=0x108000}
The basic structure of the two receivers:
public class MyReceiverA extends BroadcastReceiver {
public static final String ACTION_TO_BROADCAST = "my.package.action.a";
public void onReceive(Context context, Intent intent) {
// start the service
Intent serviceIntent = new Intent().setClassName(context,
MyServiceA.class.getName());
context.startService(serviceIntent);
}
}
And the services:
public class MyServiceA extends IntentService {
public ActivityMonitorService() {
super(TAG);
}
public IBinder onBind(Intent intent) {
// We don't allow anyone to bind to us
return null;
}
public void onCreate() {
super.onCreate();
_context = getApplicationContext();
_config = new Config();
if (_handler == null) {
_handler = new Handler();
}
}
/**
* Schedules an alarm to run ourselves again after ALARM_INTERVAL has passed.
*/
private void reschedule() {
Intent intent = new Intent(MyReceiverA.ACTION_TO_BROADCAST);
PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, 0, intent, 0);
AlarmManager manager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, now + delay, pendingIntent);
}
private void doWork() {
// Do some work. This could take a while. It also accesses a database that the two
// services share through synchronized blocks of code in static accessor functions.
}
protected void onHandleIntent(Intent intent) {
try {
doWork();
} catch (Exception e) {
// log it
} finally {
reschedule();
}
}
}
I figured out what was going on. Changing the two services to be a single one fixed the problem, meaning there was some sort of deadlock or race going on in the two. I'm assuming it's with their database access but haven't had a chance to verify it yet.
When changing to a single service the problem wasn't that the alarm was firing late, it's that the loaded down phone was pausing my service to give the music player the resources it needed. Looks like my options are to live with it or run the service in the foreground.

stopService doesn't stop's my service.... why?

i have a background service on my android APP that is getting my GPS position and sending it to a remote db. It work's fine.
The problem is when i want to stop the service.... it doesn't stops :S. Also no exception or errors on logcat have appeared... it simply doesn't stops.
this is the code to start my srvice (with a button):
startService(new Intent(GPSLoc.this, MyService.class)); //enciendo el service
this is the code where I stop it (on the onactivityresult method):
stopService(new Intent(GPSLoc.this, MyService.class));
I have been debugged the app, and i checked that the stopService codeline has been called every time that i debugged it, but it doesn't stops......
i am sure that it's not stopped cause on my database i still recive gps positions from the emulator when i have press the button to stop the service.
what i am doing bad?
Have you implemented onDestroy()? If not, I believe that might be the solution - and you stop your Timer or whatever you're using to run the service within onDestroy().
A service can be stopped by calling its stopSelf() method, or by calling Context.stopService().
See this link for some more information.
i am sure that it's not stopped cause on my database i still recive gps positions from the emulator when i have press the button to stop the service.
You probably are not unregistering your LocationListener.
I had the same problem. I found that if the service has GoogleApiClient connected and still get location update, the stopService() has totally no effect, the service's industry() was not called.
To fix the problem, I created a function to stop the location service in the service code. Call the stopLocationService() from the activity, and then call stopService. Here is the code example:
public class myLocationService extends Service{
...
public void stopLocationUpdates() {
LocationService.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
mGoogleApiClient.disconnect();
}
...
}
In activity,
{
...
if(mService != null && isBound) {
mService.stopLocationUpdates();
doUnbindService();
stopService(new Intent(this, myLocationService.class));
}
...
}
It's very common this situation where I need to stop my service before to finish the process. In some case is not enough with stopService(intent). You should have in mind the onDestroy() implement in my service. Example:
public class MyIntentService extends IntentService {
// Defines and instantiates an object for handling status updates.
private BroadcastNotifier mBroadcaster = null;
private int progress = 0; //THIS IS MY COUNTER FOR EXAMPLE!!!
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
progress = 0;
int tiempo_disponible = intent.getIntExtra("minutos_disponible", 0);
if (mBroadcaster == null){
mBroadcaster = new BroadcastNotifier(this);
}
// Broadcasts an Intent indicating that processing has started.
mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);
mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_RUNNING);
while (progress < tiempo_disponible) {
progress++;
try {
Log.i(Constants.TAG, "Procesing " + progress);
mBroadcaster.notifyProgress(progress);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Reports that the feed retrieval is complete.
mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
}
#Override
public void onDestroy() {
progress = 1000000; // WHITH THAT YOU FINISH THE CICLE IF tiempo_disponible NEVER IS MAYOR THAT 1000000, YOU CAN USE OTHER CONDITIONAL!!!!!!
super.onDestroy();
}
}
In this way, when you have stopped the service using stopService method also you will have stopped the process o counter.
public void stopService(){
context.stopService(intent);
LocalBroadcastManager.getInstance(context).unregisterReceiver(responseReceiver);
responseReceiver = null;
intent = null;
}
Take care!
#yaircarreno
If you are tracking GPS location, you probably used GoogleApiClient.
The concept is that the Service WILL NOT stop,
if an GoogleApiClient instance is still connected within it.
(Or any other issue that need to be destroyed / unregistered first)
So to make it works, implement onDestroy() within your service:
#Override
public void onDestroy()
{
// Unregistered or disconnect what you need to
// For example: mGoogleApiClient.disconnect();
super.onDestroy();
}
I have found the best way to stop a service is to make stop itself. This way you are sure it actually will stop and preserve data integrity. If you want to do it from outside (activity) I usually use a global static attribute.
Per example (Kotlin) if I have MyService, MyActivity and MyObject
My Object
object MyObject{
abort = false
}
MyService
override fun onHandleIntent(intent: Intent?) {
startForeground(id,notification)
for (i in range){
if (MyObject.abort) break
// RUN SOME CODE HERE
}
stopForeground(true)
stopSelf()
}
MyActivity
fun startService() {
startForegroundService(Intent(this, OptimizationService::class.java))
}
fun stopService() {
MyObject.abort = true
}
it could be perhaps that you are creating a new Intent everytime you call the stop service.
stopService(new Intent(GPSLoc.this, MyService.class));
perhaps try :
Intent intnet = new Intent(GPSLoc.this, MyService.class); // create el service
startService(intenet);
stopService(intent);
For those who want to send a request to server periodically, this is my solution. You should have this in your Activity or Fragment Activity
{
private static final Long UPDATE_LOCATION_TIME = 30 * 60 * 1000l; // 30 minute
private AlarmManager alarm;
private PendingIntent pIntent;
...
#Override
protected void onResume() {
super.onResume();
// Run background service in order to update users location
startUserLocationService();
Log.e(TAG, "onResume");
}
#Override
protected void onStop() {
super.onStop();
stopUserLocationService();
Log.e(TAG, "onStop");
}
private void startUserLocationService() {
Log.i(TAG, "Starting service...");
Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class);
pIntent = PendingIntent.getService(this, 0, intent, 0);
alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), UPDATE_LOCATION_TIME, pIntent);
}
private void stopUserLocationService() {
alarm.cancel(pIntent);
Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class);
stopService(intent);
}
}
my problem solved by removing the added views to WindowManager ondestroy
public void onDestroy() {
isRunning = false;
super.onDestroy();
if (checkBox!=null) {
windowManager.removeView(getlayoutparm(fabsetting,fabrateus,fabexit,true));
windowManager.removeView(checkBox);
}
}
In my case the stopService is called with startService almost simultaneously so no service is there to be stopped. Try delay stopService for a few seconds. :)
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.d(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}

Categories

Resources