| | |
| | | import android.annotation.SuppressLint; |
| | | import android.content.Context; |
| | | import android.content.pm.PackageManager; |
| | | import android.location.Address; |
| | | import android.location.Geocoder; |
| | | import android.location.Location; |
| | | import android.location.LocationListener; |
| | | import android.location.LocationManager; |
| | | import android.os.Bundle; |
| | | |
| | | |
| | | import java.io.IOException; |
| | | import java.math.BigDecimal; |
| | | import java.math.RoundingMode; |
| | | import java.util.List; |
| | | import java.util.Locale; |
| | | |
| | | import androidx.annotation.NonNull; |
| | | import androidx.core.app.ActivityCompat; |
| | |
| | | return Singleton.INSTANCE; |
| | | } |
| | | |
| | | public String getCountryCode(Context context) throws IOException { |
| | | LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); |
| | | if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { |
| | | // 处理权限请求 |
| | | return null; |
| | | } |
| | | Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); |
| | | if (location == null) { |
| | | location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); |
| | | } |
| | | if (location != null) { |
| | | Geocoder geocoder = new Geocoder(context, Locale.getDefault()); |
| | | List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); |
| | | if (addresses != null && !addresses.isEmpty()) { |
| | | return addresses.get(0).getCountryCode(); |
| | | } |
| | | } |
| | | |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 开启定位 |
| | | */ |