9

I want to do something like this:

  • When my application starts I want to start a Service which should check my location

  • When the application goes to background I want to stop the service

I have two major problems:

  1. How can I detect that my application goes to background? I haver several activities, and I tried that in my MainActivity overriding onPause, but the onPause is also called when I start an other activity.

  2. This problem is more important: How should my Service which checks for my location look like? I tried several approaches, but no success.

My Service looks like this, and it's not working. What should I change to make it work?

package com.pivoscore.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class LocationService extends Service {

    private LocationListener locationListener;

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

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

    @Override
    public void onCreate() {
        super.onCreate();
        final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        this.locationListener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, this.locationListener);
    }

    private static class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(final Location location) {
        }

        @Override
        public void onProviderDisabled(final String provider) {
        }

        @Override
        public void onProviderEnabled(final String provider) {
        }

        @Override
        public void onStatusChanged(final String provider, final int status, final Bundle extras) {
        }

    }

}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
dfritsi
  • 1,224
  • 3
  • 14
  • 24
  • onResume() method, let the service search Location Information and onPause() method remove the Location. – user2060383 Feb 25 '13 at 12:06
  • I want to use my location in several activities, not only in the main activity. So it would not be wise to stop the Service in onPause, because if an other activity comes to front, onPause will be called, and I would stop getting the location updates. – dfritsi Feb 25 '13 at 12:08
  • android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION android.permission.ACCESS_NETWORK_STATE have you added these Permission in your manifest file ? – Usman Kurd Feb 25 '13 at 13:07

2 Answers2

2
  1. Application is not a visual component in Android. It is divided into Activities, each of them run when visible, paused and destroyed otherwise. So, there is no concept of whole Application going to background, Activities are paused and resumed on the basis of their individual visibility and are completely independent of other Activities in this matter.

  2. Your Service shall register with Location Manager in its onCreate(), unregister from the same in its onDestroy(). In its onBind() it shall return a Messenger object. And, in onLocationChanged() it should send a message through its shared Messenger. No need to use START_STICKY as you don't want Service running all the time.

  3. The Activity (can be any activity in the App) just needs to call bindService() in its onStart(), The service will start if not already, and Activity will get a Messenger from service. Also, Activity should call unbindService() from its onStop(). The Service will automatically stop when nothing is bound to it.

  4. If you need to do the stuff in point 3 at App (Task) level, implement the Application class, and use its onCreate() and onTerminate(). Application class is not paused or stopped like an Activity.

S.D.
  • 29,290
  • 3
  • 79
  • 130
  • How can I detect that my APPLICATION goes to background? I never said about any activity going to background. But that doesn't matter anymore, because my first problem is solved. – dfritsi Feb 25 '13 at 12:49
  • There is no **Visible Application** component in Android. If any one of your Activity is visible, App is running, else, App is stopped and may be even destroyed. Still, you can use point 4. – S.D. Feb 25 '13 at 12:59
0

Try This code.. By using this you can find whether your application is in foreground or background. Hope this will help you.

try {
    foreground = new ForegroundCheckTask().execute(ctx).get();
}

======================================


class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

@Override
protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
}

private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager
            .getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    final String packageName = context.getPackageName();


    String activePackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
    if (activePackageName.equals(packageName)) {
        return true;
    }
    else{
        return false;
    }


}

}
itsrajesh4uguys
  • 4,610
  • 3
  • 20
  • 31
  • ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION for future location code nothing more, just remember to add each service to your AndroidManifest – akuzma Feb 25 '13 at 12:28
  • no permissions.. just use context that's it.. and foreground is an boolean value.. ctx is Context ..use it and let me know your comments. – itsrajesh4uguys Feb 25 '13 at 12:28
  • Okay. The problem with my Service was that I can't use NETWORK_PROVIDER in an emulator. So it was my mistake. Sorry. It works on my phone. – dfritsi Feb 25 '13 at 14:30
  • k... you can test the network provider in your emulator too.. goto DMS-> Select the Particular Emulator-> Goto Emulator control -> Inthat you will have location controls. change the co-ordinations according to you.. then send it .. now your emulator will provide the location .. – itsrajesh4uguys Feb 25 '13 at 14:35