修改名称。

This commit is contained in:
2025-11-07 09:22:39 +08:00
parent d9cf55b053
commit a8dcfbb6a7
2203 changed files with 3 additions and 4 deletions

View File

@@ -0,0 +1,94 @@
package com.xscm.moduleutil.utils.location;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GmsLocationProvider implements LocationProvider {
private static final String TAG = "GmsLocationProvider";
private FusedLocationProviderClient fusedLocationClient;
private LocationCallback locationCallback;
public GmsLocationProvider(Context context) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
}
@SuppressLint("MissingPermission")
@Override
public void getLastKnownLocation(Context context, LocationCallback callback) {
fusedLocationClient.getLastLocation()
.addOnSuccessListener(location -> {
if (location != null) {
String city = getCityName(context, location.getLatitude(), location.getLongitude());
callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
} else {
callback.onFailed("无法获取位置");
}
})
.addOnFailureListener(e -> callback.onFailed("Google Play 定位失败:" ));
}
@SuppressLint("MissingPermission")
@Override
public void requestLocationUpdates(Context context, LocationCallback callback) {
this.locationCallback = new LocationCallback() {
@Override
public void onLocationReceived(double latitude, double longitude, String city) {
// for (android.location.Location location : locationResult.getLocations()) {
String city1 = getCityName(context, latitude, longitude);
callback.onLocationReceived(latitude, longitude, city1);
// }
}
@Override
public void onFailed(String errorMessage) {
}
// @Override
// public void onLocationResult(@NonNull LocationResult locationResult) {
// for (android.location.Location location : locationResult.getLocations()) {
// String city = getCityName(context, location.getLatitude(), location.getLongitude());
// callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
// }
// }
};
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000)
.setFastestInterval(5000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationClient.requestLocationUpdates(locationRequest, (com.google.android.gms.location.LocationCallback) locationCallback, null);
}
@Override
public void stopLocationUpdates() {
if (locationCallback != null) {
fusedLocationClient.removeLocationUpdates((com.google.android.gms.location.LocationCallback) locationCallback);
}
}
private String getCityName(Context context, double latitude, double longitude) {
android.location.Geocoder geocoder = new android.location.Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
return addresses.get(0).getLocality();
}
} catch (IOException e) {
Log.e(TAG, "地理编码失败", e);
}
return "未知城市";
}
}

View File

@@ -0,0 +1,65 @@
package com.xscm.moduleutil.utils.location;
import android.content.Context;
import android.os.AsyncTask;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class IpLocationProvider implements LocationProvider {
@Override
public void getLastKnownLocation(Context context, LocationCallback callback) {
new FetchIpLocationTask(callback).execute();
}
@Override
public void requestLocationUpdates(Context context, LocationCallback callback) {
getLastKnownLocation(context, callback); // 单次定位即可
}
@Override
public void stopLocationUpdates() {}
private static class FetchIpLocationTask extends AsyncTask<Void, Void, String> {
private final LocationCallback callback;
FetchIpLocationTask(LocationCallback callback) {
this.callback = callback;
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://ip-api.com/json/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
JSONObject obj = new JSONObject(Boolean.parseBoolean(json.toString()));
return obj.getString("city");
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String city) {
if (city != null && !city.isEmpty()) {
callback.onLocationReceived(0, 0, city);
} else {
callback.onFailed("IP 定位失败");
}
}
}
}

View File

@@ -0,0 +1,21 @@
package com.xscm.moduleutil.utils.location;
import android.content.Context;
public interface LocationProvider {
void getLastKnownLocation(Context context, LocationCallback callback);
void requestLocationUpdates(Context context, LocationCallback callback);
void stopLocationUpdates();
interface LocationCallback {
void onLocationReceived(double latitude, double longitude, String city);
void onFailed(String errorMessage);
}
// interface LocationCallback {
// void onLocationReceived(double latitude, double longitude, String city);
// void onFailed(String errorMessage);
// }
}

View File

@@ -0,0 +1,24 @@
package com.xscm.moduleutil.utils.location;
import android.content.Context;
public class LocationServiceFactory {
public static LocationProvider createBestProvider(Context context) {
if (false) {
return new GmsLocationProvider(context);
} else {
return new SystemLocationProvider();
}
}
private static boolean isGooglePlayServicesAvailable(Context context) {
// 实现判断逻辑,例如使用 GoogleApiAvailability
// 或者简单尝试加载类是否存在
try {
Class.forName("com.google.android.gms.common.GoogleApiAvailability");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}

View File

@@ -0,0 +1,258 @@
package com.xscm.moduleutil.utils.location;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import com.blankj.utilcode.util.ToastUtils;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class SystemLocationProvider implements LocationProvider {
private LocationManager locationManager;
public void getLastKnownLocation(@NonNull Context context, @NonNull LocationCallback callback) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null) {
callback.onFailed("无法获取定位服务");
return;
}
Log.d("LocationDebug", "LocationManager 初始化成功");
try {
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.d("LocationDebug", "GPS Enabled: " + isGpsEnabled);
Log.d("LocationDebug", "Network Enabled: " + isNetworkEnabled);
if (!isGpsEnabled && !isNetworkEnabled) {
callback.onFailed("GPS 和 网络定位均未启用");
return;
}
final Handler handler = new Handler(Looper.getMainLooper());
Runnable timeout = () -> callback.onFailed("定位请求超时");
handler.postDelayed(timeout, 15000); // 15秒超时
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
handler.removeCallbacks(timeout);
String city = getCityName(context, location.getLatitude(), location.getLongitude());
callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("LocationDebug", "onStatusChanged: " + provider + ", status: " + status);
}
@Override
public void onProviderEnabled(@NonNull String provider) {
Log.d("LocationDebug", "onProviderEnabled: " + provider);
}
@Override
public void onProviderDisabled(@NonNull String provider) {
Log.d("LocationDebug", "onProviderDisabled: " + provider);
fallbackToNetwork(callback, context);
}
};
if (isNetworkEnabled) {
Log.d("LocationDebug", "尝试使用 NETWORK 定位");
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, listener, Looper.getMainLooper());
}
else if (isGpsEnabled) {
Log.d("LocationDebug", "尝试使用 GPS 定位");
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, listener, Looper.getMainLooper());
}
} catch (SecurityException e) {
Log.e("LocationDebug", "缺少定位权限", e);
callback.onFailed("缺少定位权限:" + e.getMessage());
}
}
// @Override
// public void getLastKnownLocation(@NonNull Context context, @NonNull LocationCallback callback) {
// locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// if (locationManager == null) {
// callback.onFailed("无法获取定位服务");
// return;
// }
//
// try {
// if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
// @Override
// public void onLocationChanged(@NonNull Location location) {
// String city = getCityName(context, location.getLatitude(), location.getLongitude());
// callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
// ToastUtils.showShort(provider);
// }
//
// @Override
// public void onProviderEnabled(@NonNull String provider) {
// ToastUtils.showShort(provider);
// }
//
// @Override
// public void onProviderDisabled(@NonNull String provider) {
// fallbackToNetwork(callback, context);
// }
// }, Looper.getMainLooper());
// } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
// @Override
// public void onLocationChanged(@NonNull Location location) {
// String city = getCityName(context, location.getLatitude(), location.getLongitude());
// callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
// ToastUtils.showShort(provider);
// }
//
// @Override
// public void onProviderEnabled(@NonNull String provider) {
// ToastUtils.showShort(provider);
// }
//
// @Override
// public void onProviderDisabled(@NonNull String provider) {
// callback.onFailed("网络定位不可用");
// }
// }, Looper.getMainLooper());
// } else {
// callback.onFailed("GPS 和 网络定位均未启用");
// }
// } catch (SecurityException e) {
// callback.onFailed("缺少定位权限:" + e.getMessage());
// }
// }
private void fallbackToNetwork(LocationCallback callback, Context context) {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
String city = getCityName(context, location.getLatitude(), location.getLongitude());
callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
ToastUtils.showShort(provider);
}
@Override
public void onProviderEnabled(@NonNull String provider) {
ToastUtils.showShort(provider);
}
@Override
public void onProviderDisabled(@NonNull String provider) {
callback.onFailed("网络定位不可用");
}
}, Looper.getMainLooper());
} else {
callback.onFailed("GPS 不可用且网络定位也未启用");
}
}
@Override
public void requestLocationUpdates(Context context, LocationCallback callback) {
// 可扩展为持续监听
}
@Override
public void stopLocationUpdates() {
// 可扩展为停止监听
}
private String getCityName(Context context, double latitude, double longitude) {
android.location.Geocoder geocoder = new android.location.Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
return addresses.get(0).getAdminArea() + "," + addresses.get(0).getLocality()+ "," + addresses.get(0).getSubLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
return "未知城市";
}
public void useNetworkLocation(Context context, LocationCallback callback) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null) {
callback.onFailed("无法获取定位服务");
return;
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
callback.onFailed("缺少定位权限");
return;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
String city = getCityName(context, location.getLatitude(), location.getLongitude());
callback.onLocationReceived(location.getLatitude(), location.getLongitude(), city);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
ToastUtils.showShort(provider);
}
@Override
public void onProviderEnabled(@NonNull String provider) {
ToastUtils.showShort(provider);
}
@Override
public void onProviderDisabled(@NonNull String provider) {
callback.onFailed("网络定位不可用");
}
}, Looper.getMainLooper());
} else {
callback.onFailed("网络定位未启用");
}
}
}