Use service to get GPS location, android?

假装没事ソ 提交于 2019-12-01 10:47:46

问题


This is first time I am using service and it sure looks a lot complicated from activity.

So I am trying to get the user's location after he has closed my application with the service.

This is my service class.

public class LocTrack extends Service {


GPSTracker gp;
@Override
public void onCreate() 
{    gp = new GPSTracker(getApplicationContext());
    onLocationChanged(gp);
    super.onCreate();        
}
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub

    return Service.START_STICKY;
}


@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public void onLocationChanged(GPSTracker track) {


    // Getting latitude
    double latitude = track.getLatitude();

    // Getting longitude
    double longitude = track.getLongitude();

     Geocoder geocoder = new Geocoder(LocTrack.this, Locale.getDefault());

    try
     {
         List<Address> addresses = geocoder.getFromLocation(latitude, longitude,1);
         Log.e("Addresses","-->"+addresses);

     }
     catch (IOException e)
     {
         e.printStackTrace();

     }

}
}

Please tell me what am I doing my wrong. If I use the code in an activity class then I am able to get the address in the logcat but not when i use service.

This is how i am calling the service from activity

    Intent intent = new Intent(MainActivity.this, LocTrack.class);
             startService(intent);

回答1:


The best way would be to use location services by CWAC Location Poller service is already made for us to use it just you have to give the time interval to wake up it

Do it like dis way n you'll need the jar file which you can get it from https://www.dropbox.com/sh/pgxk2v9l5vl0h2j/3svyZnuwOK/CWAC-LocationPoller.jar

From your activity start LocationPoller and set the alarm repeating to the time you want

AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, LocationPoller.class);

Bundle bundle = new Bundle();
LocationPollerParameter parameter = new LocationPollerParameter(bundle);
parameter.setIntentToBroadcastOnCompletion(new Intent(this,
        LocationReceiver.class));
// try GPS and fall back to NETWORK_PROVIDER
parameter.setProviders(new String[] { LocationManager.GPS_PROVIDER,
        LocationManager.NETWORK_PROVIDER });
parameter.setTimeout(120000);
i.putExtras(bundle);

PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime(), 300000, pi);

Make a receiver class Location Receiver from where you'll fetch the lat n lon

public class LocationReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {


    try {      
      Bundle b=intent.getExtras();

      LocationPollerResult locationResult = new LocationPollerResult(b);

      Location loc=locationResult.getLocation();
      String msg;

      if (loc==null) {
        loc=locationResult.getLastKnownLocation();

        if (loc==null) {
          msg=locationResult.getError();
        }
        else {
          msg="TIMEOUT, lastKnown="+loc.toString();
        }
      }
      else {
        msg=loc.toString();



        Log.i("Location Latitude", String.valueOf(loc.getLatitude()));
        Log.i("Location Longitude", String.valueOf(loc.getLongitude()));
        Log.i("Location Accuracy", String.valueOf(loc.getAccuracy()));




      }

      Log.i(getClass().getSimpleName(), "received location: " + msg);   



    }
    catch (Exception e) {
      Log.e(getClass().getName(), e.getMessage());
    }
  }

and add this to your manifest

   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

   <receiver android:name="com.commonsware.cwac.locpoll.LocationPoller" />

   <service android:name="com.commonsware.cwac.locpoll.LocationPollerService" />

and the receiver declaration where you'll fetch everything

   <receiver android:name="com.RareMediaCompany.Helios.LocationReceiver" />


来源:https://stackoverflow.com/questions/18051958/use-service-to-get-gps-location-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!