在Android M中获取经度0.0

在Android M中获取经度0.0,第1张

在Android M中获取经度0.0

借助 CommonsWareBlackkara的 答案,我能够解决我的问题。

根据他们的建议,我更改了代码,并通过调试仔细检查了代码的每个步骤。

因此,我遇到了这样的问题:在棉花糖的情况下,我的onLocationChanged()没有被解雇,但是令人惊讶的是,在低于Android
M或6.0的旧设备中,它却被解雇了。

为了解决这个问题,我更改了代码,如下所示,在此发布完整的代码,以便任何有相同问题的人都可以摆脱。

GPSTracker.java

public class GPSTracker extends Service{    private  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 = 1000; // 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;    Activity activity;    public GPSTracker() {    }    public GPSTracker(Context context, Activity activity) {        this.mContext = context;        this.activity = activity;        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;     if (isNetworkEnabled) {         int requestPermissionsCode = 50;         locationManager.requestLocationUpdates(      LocationManager.NETWORK_PROVIDER,      MIN_TIME_BW_UPDATES,      MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);         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 latitude/longitude using GPS Services if (isGPSEnabled) {     if (location == null) {         if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {  ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);         } else {  locationManager.requestLocationUpdates(          LocationManager.GPS_PROVIDER,          MIN_TIME_BW_UPDATES,          MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);  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;    }        public void stopUsingGPS() {    }    private final LocationListener mLocationListener = new LocationListener() {        @Override        public void onLocationChanged(final Location location) { if (location != null) {     latitude = location.getLatitude();     longitude = location.getLongitude(); }        }        @Override        public void onStatusChanged(String provider, int status, Bundle extras) {        }        @Override        public void onProviderEnabled(String provider) {        }        @Override        public void onProviderDisabled(String provider) {        }    };        public double getLatitude(){        if(location != null){ latitude = location.getLatitude();        }        // return latitude        return latitude;    }        public double getLongitude(){        if(location != null){ longitude = location.getLongitude();        }        // return longitude        return longitude;    }        public boolean canGetLocation() {        return this.canGetLocation;    }        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 the 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 the cancel button        alertDialog.setNegativeButton("Cancel", new DialogInterface.onClickListener() { public void onClick(DialogInterface dialog, int which) {     dialog.cancel(); }        });        // Showing alert Message        alertDialog.show();    }    @Override    public IBinder onBind(Intent arg0) {        return null;    }}

DashboardActivity.java

public class DashboardActivity extends Activity {    Context mContext;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_dashboard);        mContext = this;        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);        } else { Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show(); gps = new GPSTracker(mContext, DashboardActivity.this); // Check if GPS enabled if (gps.canGetLocation()) {     double latitude = gps.getLatitude();     double longitude = gps.getLongitude();     // n is for new line     Toast.makeText(getApplicationContext(), "Your Location is - nLat: " + latitude + "nLong: " + longitude, Toast.LENGTH_LONG).show(); } else {     // Can't get location.     // GPS or network is not enabled.     // Ask user to enable GPS/network in settings.     gps.showSettingsalert(); }        }    }    @Override    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {        super.onRequestPermissionsResult(requestCode, permissions, grantResults);        switch (requestCode) { case 1: {     // If request is cancelled, the result arrays are empty.     if (grantResults.length > 0  && grantResults[0] == PackageManager.PERMISSION_GRANTED) {         // permission was granted, yay! Do the         // contacts-related task you need to do.         gps = new GPSTracker(mContext, DashboardActivity.this);         // Check if GPS enabled         if (gps.canGetLocation()) {  double latitude = gps.getLatitude();  double longitude = gps.getLongitude();  // n is for new line  Toast.makeText(getApplicationContext(), "Your Location is - nLat: " + latitude + "nLong: " + longitude, Toast.LENGTH_LONG).show();         } else {  // Can't get location.  // GPS or network is not enabled.  // Ask user to enable GPS/network in settings.  gps.showSettingsalert();         }     } else {         // permission denied, boo! Disable the         // functionality that depends on this permission.         Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();     }     return; }        }    }}

Manifest.xml:

添加的权限

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

在应用程序标签中声明服务:

 <service android:name=".utilities.GPSTracker"/>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5615809.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存