【问题标题】:How to get current Location(latitude , longitude) while gps is off using FusedLocationApi in android如何在gps关闭时在android中使用FusedLocationApi获取当前位置(纬度,经度)
【发布时间】:2015-10-31 18:18:57
【问题描述】:

我使用了最新的 api。我已经实现了 FusedLocationApi,如果 gps 开启,我将获得当前位置。我已经连接了 google play 服务,但我仍然没有获得当前位置。

我使用这个代码:

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.provider.Settings;

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;

public class GPSTracker implements ConnectionCallbacks,
        OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private OnLocationChangedListener mLocationChangedListener;

    // The minimum distance to change Updates in meters
    private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            MIN_TIME_BW_UPDATES / 2;
    private final Context mContext;
    // Declaring a Location Manager
    protected LocationRequest mLocationRequest;
    // flag for GPS status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    // Current best location estimate
    private Location mBestReading;
    private GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation; // location
    double latitude; // latitude
    double longitude; // longitude


    public void setLocationChangedListener(OnLocationChangedListener listener) {
        mLocationChangedListener = listener;
    }


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

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mCurrentLocation != null)
                canGetLocation = true;
        }

        mGoogleApiClient.connect();
    }


    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        // Sets the desired interval for active location updates. This interval is
        // inexact. You may not receive updates at all if no location sources are available, or
        // you may receive them slower than requested. You may also receive updates faster than
        // requested if other applications are requesting location at a faster interval.
        mLocationRequest.setInterval(MIN_TIME_BW_UPDATES);

        // Sets the fastest rate for active location updates. This interval is exact, and your
        // application will never receive updates faster than this value.
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

        mLocationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


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

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (mCurrentLocation != null) {
            longitude = mCurrentLocation.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 is settings");

        // 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();
    }


    /**
     * Removes location updates from the FusedLocationApi.
     */
    protected void stopLocationUpdates() {
        // It is a good practice to remove location requests when the activity is in a paused or
        // stopped state. Doing so helps battery performance and is especially
        // recommended in applications that request frequent location updates.

        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    /**
     * Requests location updates from the FusedLocationApi.
     */
    protected void startLocationUpdates() {
        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }


    @Override
    public void onLocationChanged(Location mCurrentLocation) {
        canGetLocation = true;
        this.mCurrentLocation = mCurrentLocation;
        mLocationChangedListener.onReceiveLocation(mCurrentLocation, 1);
        stopLocationUpdates();
    }


    @Override
    public void onConnected(Bundle bundle) {
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mCurrentLocation != null) {
                canGetLocation = true;
                mLocationChangedListener.onReceiveLocation(mCurrentLocation, 1);
            }
        }
        if (mCurrentLocation == null && mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }


    public interface OnLocationChangedListener {
        void onReceiveLocation(Location receiveLocation, int resultCode);
    }

}

这里是代码。 GPS 关闭时,Api 未调用 onLocationChanged(Location location) 回调方法。

【问题讨论】:

    标签: android gps location


    【解决方案1】:

    没有 GPS 是不可能更新当前纬度的。以下代码在 GPS 开启时工作,但在某些情况下,如果 AGPS 从 wifi 连接或电信网络获取 lat long,GPS 能够跟踪当前的 lat long,并且它仅在设备具有AGPS 硬件。

    import android.location.Location;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    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.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import java.text.DateFormat;
    import java.util.Date;
    
    /**
     * Getting Location Updates.
     *
     * Demonstrates how to use the Fused Location Provider API to get updates about a device's
     * location. The Fused Location Provider is part of the Google Play services location APIs.
     *
     * For a simpler example that shows the use of Google Play services to fetch the last known location
     * of a device, see
     * https://github.com/googlesamples/android-play-location/tree/master/BasicLocation.
     *
     * This sample uses Google Play services, but it does not require authentication. For a sample that
     * uses Google Play services for authentication, see
     * https://github.com/googlesamples/android-google-accounts/tree/master/QuickStart.
     */
    public class MainActivity extends ActionBarActivity implements
            ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    
        protected static final String TAG = "location-updates-sample";
    
        /**
         * The desired interval for location updates. Inexact. Updates may be more or less frequent.
         */
        public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    
        /**
         * The fastest rate for active location updates. Exact. Updates will never be more frequent
         * than this value.
         */
        public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
                UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    
        // Keys for storing activity state in the Bundle.
        protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
        protected final static String LOCATION_KEY = "location-key";
        protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
    
        /**
         * Provides the entry point to Google Play services.
         */
        protected GoogleApiClient mGoogleApiClient;
    
        /**
         * Stores parameters for requests to the FusedLocationProviderApi.
         */
        protected LocationRequest mLocationRequest;
    
        /**
         * Represents a geographical location.
         */
        protected Location mCurrentLocation;
    
        // UI Widgets.
        protected Button mStartUpdatesButton;
        protected Button mStopUpdatesButton;
        protected TextView mLastUpdateTimeTextView;
        protected TextView mLatitudeTextView;
        protected TextView mLongitudeTextView;
    
        /**
         * Tracks the status of the location updates request. Value changes when the user presses the
         * Start Updates and Stop Updates buttons.
         */
        protected Boolean mRequestingLocationUpdates;
    
        /**
         * Time when the location was updated represented as a String.
         */
        protected String mLastUpdateTime;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Locate the UI widgets.
            mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
            mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
            mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
            mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
            mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
    
            mRequestingLocationUpdates = false;
            mLastUpdateTime = "";
    
            // Update values using data stored in the Bundle.
            updateValuesFromBundle(savedInstanceState);
    
            // Kick off the process of building a GoogleApiClient and requesting the LocationServices
            // API.
            buildGoogleApiClient();
            //turnGPSOn();
        }
    
        /**
         * Updates fields based on data stored in the bundle.
         *
         * @param savedInstanceState The activity state saved in the Bundle.
         */
        private void updateValuesFromBundle(Bundle savedInstanceState) {
            Log.i(TAG, "Updating values from bundle");
            if (savedInstanceState != null) {
                // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
                // the Start Updates and Stop Updates buttons are correctly enabled or disabled.
                if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
                    mRequestingLocationUpdates = savedInstanceState.getBoolean(
                            REQUESTING_LOCATION_UPDATES_KEY);
                    setButtonsEnabledState();
                }
    
                // Update the value of mCurrentLocation from the Bundle and update the UI to show the
                // correct latitude and longitude.
                if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
                    // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
                    // is not null.
                    mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
                }
    
                // Update the value of mLastUpdateTime from the Bundle and update the UI.
                if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
                    mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
                }
                updateUI();
            }
        }
    
        /**
         * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
         * LocationServices API.
         */
        protected synchronized void buildGoogleApiClient() {
            Log.i(TAG, "Building GoogleApiClient");
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            createLocationRequest();
        }
    
        /**
         * Sets up the location request. Android has two location request settings:
         * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
         * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
         * the AndroidManifest.xml.
         * <p/>
         * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
         * interval (5 seconds), the Fused Location Provider API returns location updates that are
         * accurate to within a few feet.
         * <p/>
         * These settings are appropriate for mapping applications that show real-time location
         * updates.
         */
        protected void createLocationRequest() {
            mLocationRequest = new LocationRequest();
    
            // Sets the desired interval for active location updates. This interval is
            // inexact. You may not receive updates at all if no location sources are available, or
            // you may receive them slower than requested. You may also receive updates faster than
            // requested if other applications are requesting location at a faster interval.
            mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    
            // Sets the fastest rate for active location updates. This interval is exact, and your
            // application will never receive updates faster than this value.
            mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }
    
        /**
         * Handles the Start Updates button and requests start of location updates. Does nothing if
         * updates have already been requested.
         */
        public void startUpdatesButtonHandler(View view) {
            if (!mRequestingLocationUpdates) {
                mRequestingLocationUpdates = true;
                setButtonsEnabledState();
                startLocationUpdates();
            }
        }
    
        /**
         * Handles the Stop Updates button, and requests removal of location updates. Does nothing if
         * updates were not previously requested.
         */
        public void stopUpdatesButtonHandler(View view) {
            if (mRequestingLocationUpdates) {
                mRequestingLocationUpdates = false;
                setButtonsEnabledState();
                stopLocationUpdates();
            }
        }
    
        /**
         * Requests location updates from the FusedLocationApi.
         */
        protected void startLocationUpdates() {
            // The final argument to {@code requestLocationUpdates()} is a LocationListener
            // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    
        /**
         * Ensures that only one button is enabled at any time. The Start Updates button is enabled
         * if the user is not requesting location updates. The Stop Updates button is enabled if the
         * user is requesting location updates.
         */
        private void setButtonsEnabledState() {
            if (mRequestingLocationUpdates) {
                mStartUpdatesButton.setEnabled(false);
                mStopUpdatesButton.setEnabled(true);
            } else {
                mStartUpdatesButton.setEnabled(true);
                mStopUpdatesButton.setEnabled(false);
            }
        }
    
        /**
         * Updates the latitude, the longitude, and the last location time in the UI.
         */
        private void updateUI() {
            if (mCurrentLocation != null) {
                mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
                mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
                mLastUpdateTimeTextView.setText(mLastUpdateTime);
            }
        }
    
        /**
         * Removes location updates from the FusedLocationApi.
         */
        protected void stopLocationUpdates() {
            // It is a good practice to remove location requests when the activity is in a paused or
            // stopped state. Doing so helps battery performance and is especially
            // recommended in applications that request frequent location updates.
    
            // The final argument to {@code requestLocationUpdates()} is a LocationListener
            // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onResume() {
            super.onResume();
            // Within {@code onPause()}, we pause location updates, but leave the
            // connection to GoogleApiClient intact.  Here, we resume receiving
            // location updates if the user has requested them.
    
            if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
                startLocationUpdates();
            }
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
            if (mGoogleApiClient.isConnected()) {
                stopLocationUpdates();
            }
        }
    
        @Override
        protected void onStop() {
            mGoogleApiClient.disconnect();
    
            super.onStop();
        }
    
        /**
         * Runs when a GoogleApiClient object successfully connects.
         */
        @Override
        public void onConnected(Bundle connectionHint) {
            Log.i(TAG, "Connected to GoogleApiClient");
    
            // If the initial location was never previously requested, we use
            // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
            // its value in the Bundle and check for it in onCreate(). We
            // do not request it again unless the user specifically requests location updates by pressing
            // the Start Updates button.
            //
            // Because we cache the value of the initial location in the Bundle, it means that if the
            // user launches the activity,
            // moves to a new location, and then changes the device orientation, the original location
            // is displayed as the activity is re-created.
            if (mCurrentLocation == null) {
                mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
                updateUI();
            }
    
            // If the user presses the Start Updates button before GoogleApiClient connects, we set
            // mRequestingLocationUpdates to true (see startUpdatesButtonHandler()). Here, we check
            // the value of mRequestingLocationUpdates and if it is true, we start location updates.
            if (mRequestingLocationUpdates) {
                startLocationUpdates();
            }
        }
    
        /**
         * Callback that fires when the location changes.
         */
        @Override
        public void onLocationChanged(Location location) {
            mCurrentLocation = location;
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateUI();
            Toast.makeText(this, getResources().getString(R.string.location_updated_message),
                    Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onConnectionSuspended(int cause) {
            // The connection to Google Play services was lost for some reason. We call connect() to
            // attempt to re-establish the connection.
            Log.i(TAG, "Connection suspended");
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult result) {
            // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
            // onConnectionFailed.
            Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
        }
    
    
        /**
         * Stores activity data in the Bundle.
         */
        public void onSaveInstanceState(Bundle savedInstanceState) {
            savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
            savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
            savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
            super.onSaveInstanceState(savedInstanceState);
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用下面的课程,您将获得当前位置.. 当您的设备更改位置时,您还将获得位置..

      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) {
                      Toast.makeText(getApplicationContext(), "NO PROVIDER ENABLED",
                              Toast.LENGTH_LONG).show();
                  } else {
                      this.canGetLocation = true;
                      // First get location from Network Provider
                      if (isNetworkEnabled) {
                          locationManager.requestLocationUpdates(
                                  LocationManager.NETWORK_PROVIDER, 0, 0, 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, 0, 0, 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 is settings");
      
              // 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) {
              // TODO Auto-generated method stub
              latitude = location.getLatitude();
              longitude = location.getLongitude();
              Log.i("location==", "" + "location change");
      
          }
      
          @Override
          public void onProviderDisabled(String provider) {
              // TODO Auto-generated method stub
              Log.i("location==", "" + "on provieder disabale");
      
          }
      
          @Override
          public void onProviderEnabled(String provider) {
              // TODO Auto-generated method stub
              Log.i("location==", "" + "on provieder enable");
      
          }
      
          @Override
          public void onStatusChanged(String provider, int status, Bundle extras) {
              // TODO Auto-generated method stub
              Log.i("location==", "" + "onstatus change ");
      
          }
      
          @Override
          public IBinder onBind(Intent intent) {
              // TODO Auto-generated method stub
      
              return null;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2011-09-29
        • 2013-07-05
        • 1970-01-01
        • 2012-07-08
        • 2017-05-09
        相关资源
        最近更新 更多