没有调用com.google.android.gms.location.LocationListener的LocationChanged

时间:2015-09-23 17:24:15

标签: android

我正在创建一个服务,我在其中请求locationUpdate .But      只有当服务首次启动后才会调用LocationChanged回调。更改位置应该在2km更改时调用。我是做错了什么

       package com.example.qwerty;
     import com.google.android.gms.common.ConnectionResult;

        import com.google.android.gms.common.api.GoogleApiClient;

        import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;

        import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;

        import com.google.android.gms.location.LocationRequest;

        import com.google.android.gms.location.LocationServices;

        import com.google.android.gms.location.LocationListener;




        import android.os.IBinder;


        //Location Callback
        public class LocationService extends Service  implements ConnectionCallbacks,OnConnectionFailedListener  {

         private class locationListener  implements LocationListener   {

            public void addLocation(String loc){
                SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
                Editor edit = pref.edit();  
                String s ="";
                if(pref.contains("location")){
                      s =    pref.getString("location", "");
                     } 
                     s  = s + loc;
                     edit.putString("location",s).commit();
                    }

        public void getAddress( final double latitude , final double longitude){
                new AsyncTask<Double, Void, String>() {
                    @Override
                    protected String doInBackground(Double...params){ 
                        Geocoder geocoder = new Geocoder(LocationService.this,Locale.getDefault());
                        String result ="";
                        List<Address> addressList =null;
                        try {
                            addressList = geocoder.getFromLocation(
                                    params[0], params[1], 1);
                         if (addressList != null && addressList.size() > 0) {
                            Address address = addressList.get(0);
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                                sb.append(address.getAddressLine(i)).append("\n");
                            }
                            sb.append(address.getLocality()).append("\n");
                            sb.append(address.getPostalCode()).append("\n");
                            sb.append(address.getCountryName());
                            result = sb.toString();
                        }
                    }
                        catch (Exception e) {
                              result =e.toString(); 
                              result  = result + " " +  latitude +  "  "+  longitude;
                        } 

                        return result;
                    }
                        @Override
                        protected void onPostExecute(String result) {   
                           addLocation(result); 
                        }
                  }.execute(latitude , longitude);
        } 
         @Override
            public void onLocationChanged(Location location) {

                if(NetworkState.isNetConnected(LocationService.this)) {
                    getAddress(location.getLatitude(), location.getLongitude());                                                        
                }else{
                    addLocation(" lat " +  location.getLatitude()+ "  long " + location.getLongitude());
                } 
            }

            }


         GoogleApiClient client  =  null;
                public LocationService() {

                }

            @Override   
            public int onStartCommand(Intent intent, int flags, int startId) {
                SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
                client = new GoogleApiClient.Builder(this)
                 .addApi(LocationServices.API)
                 .addConnectionCallbacks(this)
                 .addOnConnectionFailedListener(this)
                 .build();  
                 client.connect();


               return START_STICKY;


            }
              @Override
                public void onDestroy() {


             }

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

            @Override
            public void onConnected(Bundle arg0) {
                LocationRequest mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(420000);
                mLocationRequest.setSmallestDisplacement(1000);

                LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest , new locationListener());

            }

            @Override
            public void onConnectionSuspended(int arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onConnectionFailed(ConnectionResult arg0) {


            }
        }

2 个答案:

答案 0 :(得分:-1)

In my app,I integrated this service class for getting location datas(Latitude,longitude).Make changes where ever is required.Give it a try.
You can directly call getLatitude() and getLongitude() methods in other activities to get the lat,long value.Implement the method calling as per your requirement.hope it might help you.

     public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");
        alertDialog.setCancelable(false);

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location)
    {

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

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

}

答案 1 :(得分:-1)

I got another solution that work for me.may be it helps other in near future.
1)Set up alaram for n minutes

2)On this alaram  set a  broadcast.When you receive broadcast start a service which will get the current location.

3)After getting location stop that service.

4)The same thing goes on and on.