2

I have an Android service that collects some data in a member variable of that service which occassionally (far from always) turns into null. I myself could never produce this no matter how long this service was running on an array of Android devices, so therefore I wonder if somebody sees any mistake in following (be aware this is a stripped down example that just illustrates the issue):

public class CollectionService extends Service {
    private final CollectionServiceBinder binder = new CollectionServiceBinder();
    private PowerManager.WakeLock wakeLock;
    private UserData userData; // this is the object that sometimes becomes null

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AppId");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public void startCollecting() {
        userData = new UserData();
        Notification notification = new Notification();
        // initializing notification variable

        startForeground(0xABCD, notification);

        // trigger logic that collects relevant data here, just imagine some Runnable that's triggered on a certain interval and adds data to the UserData value object.
    }

    public UserData finishCollecting() {
        try {
            userData.setFinishDate(new Date()); // throws NullPointerException every now and then.       return userData;
        } finally {
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            stopForeground(true);
            userData = null;
        }
    }

    public boolean isCollecting() {
        return userData != null;
    }

    public class CollectionServiceBinder extends Binder {
        public CollectionService getService() {
            return CollectionService.this;
        }
    }
}

The service is started in an activity using...

Intent i = new Intent(this, CollectionService.class);
getApplicationContext().startService(i);
getApplicationContext().bindService(i, serviceConnection, BIND_AUTO_CREATE); // just so the activity has a handle and can call startCollecting()/finishCollecting()

... and is unbound in onDestroy() using ...

getApplicationContext.unbindService(serviceConnection);

The ServiceConnection class looks like this:

public class MyServiceConnection implements ServiceConnection {
    private CollectionService service;

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder binder) {
        service = ((CollectionService.CollectionServiceBinder) binder).getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        service = null;
    }

    public CollectionService getCollectionService() {
        return service;
    }
}

And startCollecting is trigger in an OnClickListener like this to prevent starting twice:

if (!serviceConnection.getCollectionService().isCollecting()) {
    serviceConnection.getCollectionService().startCollecting();
}    

I believe this should all be ok but sometimes userData (as commented in the code example) will be null. Again, this happens extremely rarely (of 50.000+ active device installs on Google Play I have just received 50 reports over the course of a year, but still, I want everyone to be able to enjoy the app).

Any ideas?

1 Answer 1

1

I don't see the place where you call startCollecting which is relevant as that's where you're initializing userData, but what's probably happening is that your service is getting killed for whatever reason and then restarted. You need to do something to persist/reload data as necessary or at the very least lazy load userData so they'll start fresh.

You don't have all your code here, but it might also be relevant to note that you only acquire your wake lock in onCreate but you release it in finishCollecting. If it's possible that you call startCollecting, finishCollecting, then startCollecting again on the same Service, you're going to end up with the Service running without a wake lock held.

3
  • Hm, according to android-developers.blogspot.se/2010/04/… foreground services are not killed, therefore I don't have any saving of the state as I have in my activities. startCollecting() is called in a OnClickListener on that activity that binds to the service. The button can't be clicked twice and I know I omitted this in the example but there is a "isCollecting" method on the service which returns true if userData is not null so clicking twice on the start button should not work (at least it didn't on seven different devices I tested on).
    – SiCN
    Feb 21, 2013 at 0:33
  • @sicn: While that comment from Ms. Hackborn was true three years ago, I do not believe that it is true today. Certainly, apps that I use that have foreground services do seem to have those processes terminated (and perhaps later restarted, depending on the return value from onStartCommand()). Hence, I would guard against this occurrence in your app, and see if it clears up your problem. Feb 21, 2013 at 0:58
  • @kabuko: Thank you guys for your help, I exercised the application with a script for several hours. A foreground service seems to behave as described by Ms. Hackborn. I recorded the object ID in the logs and it was the same for hours. What did eventually crash the app was that the Button that calls finishCollecting() could be tapped twice if the user is really really fast (i.e. before stopButton.setEnabled(false) took effect). Probably depends on how fast the phone is and if the user has jittery fingers...
    – SiCN
    Feb 23, 2013 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.