Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

android - get current device location after specific interval

I want to capture current location (latitude and longitude) of android device after specific interval (say 30 mins).. My class (or service ?? not sure what to use ) will start listening to LocationManagerListener when device booting completed. What is the best way of implementing this? how we can make use of locationChanged() method in this scenario?

This is what i think it can go:

Listen for boot completed event and set alarm service:

public class OnBootReceiver extends BroadcastReceiver {
  private static final int PERIOD=1800000; // 30 minutes

  @Override
  public void onReceive(Context context, Intent intent) {

    AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(context, OnAlarmReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(context, 0,
                                              i, 0);

    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                      SystemClock.elapsedRealtime()+60000,
                      PERIOD,
                      pi);
  }
}

Listen for alarm service and initiate the location capture class or service:

 public class OnAlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {    
      WakefulIntentService.acquireStaticLock(context);  
      context.startService(new Intent(context, locationCapture.class)); 
      or 
      new locationCapture().classmethod();
    }
    }

I am not sure how locationCapture class should be implemented. Should it be normal Java class or Service class?

Any help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This the service class you can use it

public class ServiceLocation extends Service{
    private LocationManager locMan;
    private Boolean locationChanged;
    private Handler handler = new Handler();

    public static Location curLocation;
    public static boolean isService = true;

    LocationListener gpsListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (curLocation == null) {
                curLocation = location;
                locationChanged = true;
            }else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
                locationChanged = false;
                return;
            }else
                locationChanged = true;

            curLocation = location;

            if (locationChanged)
                locMan.removeUpdates(gpsListener);

        }
        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status,Bundle extras) {
            if (status == 0)// UnAvailable
            {
            } else if (status == 1)// Trying to Connect
            {
            } else if (status == 2) {// Available
            }
        }

    };

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

        curLocation = getBestLocation();

        if (curLocation == null) 
            Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
        else{
            //Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
        }

        isService =  true;
    }
    final String TAG="LocationService";
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     return super.onStartCommand(intent, flags, startId);
   }
   @Override
   public void onLowMemory() {
       super.onLowMemory();
   }

   @Override
   public void onStart(Intent i, int startId){
      handler.postDelayed(GpsFinder,1);
   }

   @Override
   public void onDestroy() {
       handler.removeCallbacks(GpsFinder);
       handler = null;
       Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
       isService = false;
   }

   public IBinder onBind(Intent arg0) {
         return null;
  }

  public Runnable GpsFinder = new Runnable(){
    public void run(){

        Location tempLoc = getBestLocation();
        if(tempLoc!=null)
            curLocation = tempLoc;
        tempLoc = null;
        handler.postDelayed(GpsFinder,1000);// register again to start after 1 seconds...        
    }
  };

    private Location getBestLocation() {
        Location gpslocation = null;
        Location networkLocation = null;

        if(locMan==null){
          locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
        }
        try {
            if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);// here you can set the 2nd argument time interval also that after how much time it will get the gps location
                gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            }
            if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
                networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
            }
        } catch (IllegalArgumentException e) {
            //Log.e(ErrorCode.ILLEGALARGUMENTERROR, e.toString());
            Log.e("error", e.toString());
        }
        if(gpslocation==null && networkLocation==null)
            return null;

        if(gpslocation!=null && networkLocation!=null){
            if(gpslocation.getTime() < networkLocation.getTime()){
                gpslocation = null;
                return networkLocation;
            }else{
                networkLocation = null;
                return gpslocation;
            }
        }
        if (gpslocation == null) {
            return networkLocation;
        }
        if (networkLocation == null) {
            return gpslocation;
        }
        return null;
    }
}

You can set time into the handler or into the requestLocationUpdates(). you need to start this service from home. As into I have set the 1 sec for both in handler and requestLocationUpdate() for getting location after 1 sec and update me.

Edited: As this service for getting current location of the user you can start from home activity and also start from boot time. With the home activity sure that if the service was stop by the user using another application like task killer then when the user launch your application then from the home this service will be start again, to start service you can do like this way

startService(new Intent(YourActivity.this,ServiceLocation.class));

When you need to stop service it will call the onDestroy() so the handler can cancel the thread to continue for getting the location.

As the GPS set with the 1 sec(1000) this will getting the gps location every 1 sec but for getting that location you need to call every time and in my case i have set to 1 sec and as per your requirement set to 30 sec. So you gps getting the location every 1 sec and using this service in handler set the 30 min. for saving battery life you can also set the different time in to the gps request method so it will save the battery life.

you can remove the comparison part of location and current location because locationlistener every time call when the location was changed and you can use the curLocation anywhere in your application to get the current location but be sure first that you have to start this service first then after you can use otherwise you getting null pointer exception when you access the latitude and longitude of this object

Hope you got some idea and I got the answer about your queries


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...