Преглед изворни кода

优化获取GPS位置的代码,解决在某些系统下启动异常的问题

niujiuru пре 4 месеци
родитељ
комит
8a108b2b70
1 измењених фајлова са 48 додато и 33 уклоњено
  1. 48 33
      app/src/main/java/com/example/yunfeiapplication/MainActivity.java

+ 48 - 33
app/src/main/java/com/example/yunfeiapplication/MainActivity.java

@@ -1,5 +1,6 @@
 package com.example.yunfeiapplication;
 
+import android.Manifest;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -150,10 +151,6 @@ public class MainActivity extends AppCompatActivity implements CustomJsonProcess
 
     /* 定位相关 */
     private LocationManager locationManager;
-    private Handler handler= new Handler(Looper.getMainLooper());
-    private Runnable locationRunnable;
-    private static final long UPDATE_INTERVAL = 10000; // 10 seconds
-    private static final float UPDATE_DISTANCE = 0; // No distance filter
 
     /* 设备操作日志相关 */
     private LogFileManager LogFileManagerOperate;
@@ -902,46 +899,65 @@ public class MainActivity extends AppCompatActivity implements CustomJsonProcess
 
     /******************************************** GPS功能部分 ********************************************/
     private void MacStartLocationUpdates() {
-
         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+        if (locationManager == null) return;
 
-        locationRunnable = new Runnable() {
-            @Override
-            public void run() {
-
-                Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
-                if (gpsLocation != null) {
-                    onLocationChanged(gpsLocation);
-                    //Latitude: 34.054956700000005, Longitude: 113.00702833333335
-                } else {
-                    // Try to request a single update
-                    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
-                        @Override
-                        public void onLocationChanged(@NonNull Location location) {
+        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
+                != PackageManager.PERMISSION_GRANTED &&
+                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
+                        != PackageManager.PERMISSION_GRANTED) {
+            return;
+        }
 
-                        }
+        String provider = getBestProvider();
+        if (provider == null) {
+            Log.e("GPS", "No Location provider available");
+            return;
+        }
 
-                        @Override
-                        public void onStatusChanged(String provider, int status, Bundle extras) {}
+        Location location = locationManager.getLastKnownLocation(provider);
 
-                        @Override
-                        public void onProviderEnabled(@NonNull String provider) {}
+        if (location != null) {
+            handleLocation(location);
+            return;
+        }
 
-                        @Override
-                        public void onProviderDisabled(@NonNull String provider) {}
-                    }, null);
+        try {
+            locationManager.requestSingleUpdate(provider, new LocationListener() {
+                @Override
+                public void onLocationChanged(Location location) {
+                    handleLocation(location);
                 }
 
-                // Schedule the next update
-                handler.postDelayed(this, UPDATE_INTERVAL);
+                @Override public void onProviderEnabled(String provider) {}
+                @Override public void onProviderDisabled(String provider) {}
+                @Override public void onStatusChanged(String provider, int status, Bundle extras) {}
+            }, null);
+
+        } catch (SecurityException | IllegalArgumentException e) {
+            e.printStackTrace();
+        }
+    }
+
+    private String getBestProvider() {
+        if (locationManager == null) return null;
+
+        try {
+            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
+                return LocationManager.GPS_PROVIDER;
             }
-        };
 
-        // Start the first update
-        handler.post(locationRunnable);
+            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
+                return LocationManager.NETWORK_PROVIDER;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return null;
     }
 
-    private void onLocationChanged(Location location) {
+    private void handleLocation(Location location) {
         double latitude = location.getLatitude();
         double longitude = location.getLongitude();
         Log.d("Location", "Latitude: " + latitude + ", Longitude: " + longitude);
@@ -955,7 +971,6 @@ public class MainActivity extends AppCompatActivity implements CustomJsonProcess
             UserGlobalVariable.setlValue("lng", String.valueOf(longitude));
             UserGlobalVariable.setlValue("lat", String.valueOf(latitude));
         }
-
     }
 
     // 检测移动数据是否开启