当前位置:   article > 正文

Android 调用原生API获取地理位置和经纬度,判断所在国家_private location getlocation()

private location getlocation()
public static boolean isCN(Context context) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String countryIso = tm.getSimCountryIso();
    boolean isCN = false;//判断是不是大陆
    if (!TextUtils.isEmpty(countryIso)) {
        countryIso = countryIso.toUpperCase(Locale.US);
        if (countryIso.contains("CN")) {
            isCN = true;
        }
    }
    return isCN;

}
/** 判断是否是国内的 SIM 卡,优先判断注册时的mcc */
public static boolean isChinaSimCard(Context c) {
    String mcc = getSimOperator(c);
    if (isOperatorEmpty(mcc)) {
        return false;
    } else {
        return mcc.startsWith("460");
    }
}

 private Location getlocation(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        // gps
        @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        // 网络定位
        @SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        return lastKnownLocation;
    }
 

   private void initLoad() {
        Location getlocation = getlocation(MyApplication.getContext());
        // 获取经纬度
        double latitude = getlocation.getLatitude();
        double longitude = getlocation.getLongitude();
        // 地理编辑器  如果想获取地理位置 使用地理编辑器将经纬度转换为省市区
        Geocoder geocoder = new Geocoder(MyApplication.getContext(), Locale.getDefault());
        try {
            List<Address> fromLocation = geocoder.getFromLocation(latitude, longitude, 1);
            Address address = fromLocation.get(0);
            String mAddressLine = address.getAddressLine(0);
            Log.i("xxx",mAddressLine.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 

Locale locale = Locale.getDefault();
String country = locale.getCountry();

 CN   就是中国

1、添加位置权限

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

2、activity实现获取经纬度,地理位置代码

  1. public class MainActivity extends AppCompatActivity {
  2. private TextView textView;
  3. private static final String[] authBaseArr = {//申请类型
  4. Manifest.permission.ACCESS_FINE_LOCATION,
  5. Manifest.permission.ACCESS_COARSE_LOCATION
  6. };
  7. private static final int authBaseRequestCode = 1;
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_main);
  12. textView = findViewById(R.id.textView);
  13. LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  14. initNavi();
  15. //权限检查的代码
  16. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  17. // TODO: Consider calling
  18. return;
  19. }
  20. locationManager.requestLocationUpdates(
  21. LocationManager.GPS_PROVIDER,//指定GPS定位提供者
  22. 1000,//指定数据更新的间隔时间
  23. 1,//位置间隔的距离为1m
  24. new LocationListener() {//监听GPS信息是否改变
  25. @Override
  26. public void onLocationChanged(Location location) {//GPS信息发送改变时回调
  27. Log.i("lgq","onLocationChanged===="+location.getProvider());
  28. }
  29. @Override
  30. public void onStatusChanged(String provider, int status, Bundle extras) {//GPS状态发送改变时回调
  31. }
  32. @Override
  33. public void onProviderEnabled(String provider) { //定位提供者启动时回调
  34. }
  35. @Override
  36. public void onProviderDisabled(String provider) { //定位提供者关闭时回调
  37. }
  38. }
  39. );
  40. Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);//获取最新的定位信息
  41. locationUpdates(location);
  42. }
  43. private boolean hasBasePhoneAuth() {
  44. PackageManager pm = getPackageManager();
  45. for (String auth : authBaseArr) {
  46. if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
  47. return false;
  48. }
  49. }
  50. return true;
  51. }
  52. private void initNavi() {
  53. // 申请权限
  54. if (android.os.Build.VERSION.SDK_INT >= 23) {
  55. if (!hasBasePhoneAuth()) {
  56. this.requestPermissions(authBaseArr, authBaseRequestCode);
  57. return;
  58. }
  59. }
  60. }
  61. public void locationUpdates(Location location){
  62. if(location != null){
  63. StringBuilder stringBuilder = new StringBuilder(); //构建一个字符串构建器,用于记录定位信息
  64. stringBuilder.append("您的位置是:\n");
  65. stringBuilder.append("经度:");
  66. stringBuilder.append(location.getLongitude());
  67. stringBuilder.append("\n纬度:");
  68. stringBuilder.append(location.getLatitude());
  69. textView.setText(stringBuilder.toString());
  70. Log.i("lgq",".....经度==="+location.getLongitude()+"...纬度+====="+location.getLatitude());
  71. String ab = getAddress(location.getLatitude(),location.getLongitude());
  72. Log.i("lgq","sssssfa===="+ab);
  73. }
  74. else{
  75. textView.setText("GPS失效啦...");
  76. }
  77. }
  78. public String getAddress(double latitude, double longitude) {
  79. Geocoder geocoder = new Geocoder(this, Locale.getDefault());
  80. try {
  81. List<Address> addresses = geocoder.getFromLocation(latitude,
  82. longitude, 1);
  83. // Address[addressLines=[0:"广东省东莞市健升大厦"],feature=健升大厦,admin=广东省,sub-admin=null,locality=东莞市,thoroughfare=null,postalCode=null,countryCode=CN,countryName=中国,hasLatitude=true,
  84. // latitude=23.025354,hasLongitude=true,longitude=113.748738,phone=null,url=null,extras=Bundle[mParcelledData.dataSize=92]]
  85. if (addresses.size() > 0) {
  86. Address address = addresses.get(0);
  87. String data = address.toString();
  88. int startCity = data.indexOf("locality=") + "locality=".length();
  89. int endCity = data.indexOf(",", startCity);
  90. String city = data.substring(startCity, endCity);
  91. int startPlace = data.indexOf("feature=") + "feature=".length();
  92. int endplace = data.indexOf(",", startPlace);
  93. String place = data.substring(startPlace, endplace);
  94. return city + place ;
  95. }
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. }
  99. return "获取失败";
  100. }
  101. }

如获取不到位置信息

加一判断即可

if (location==null){
    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER,//指定GPS定位提供者
            5000,//指定数据更新的间隔时间
            10,//位置间隔的距离为1m
            new LocationListener() {//监听GPS信息是否改变
                @Override
                public void onLocationChanged(Location location) {//GPS信息发送改变时回调
                    Log.i("lgq","onLocationChanged===="+location.getProvider());
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {//GPS状态发送改变时回调

                }

                @Override
                public void onProviderEnabled(String provider) { //定位提供者启动时回调

                }

                @Override
                public void onProviderDisabled(String provider) { //定位提供者关闭时回调

                }
            }
    );

    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//获取最新的定位信息
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/574782
推荐阅读
相关标签