android - 试图通过手机信号塔获取位置但仍返回 null

标签 android gps

我想做的是从用户那里获取位置信息。首先它尝试通过 GPS 获取位置并检查位置是否可用。如果不是,则它会尝试通过网络塔。当 GPS 打开时,它工作正常。但是当我关闭 GPS 时,它无法使用网络提供商获取位置

 manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = manager.getBestProvider(new Criteria(), false);

    Log.i("ITEMSET best", provider);


    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
    }

    Log.i("ITEMSET provider", provider);

    location = manager.getLastKnownLocation(provider);
    Log.i("ITEMSET netLoc", location + "");
    if(location==null) {
        provider = LocationManager.NETWORK_PROVIDER;
        location = manager.getLastKnownLocation(provider);
        Log.i("ITEMSET netLoc", location + "qqq");
    }



    Log.i("ITEMSET current", provider);
    Log.i("ITEMSET location", location  + "");

Logcat

Location 最初为空,因为 GPS 未打开。但随后将提供商更改为网络提供商。但位置仍然为空

最佳答案

检查网络是否开启

 isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

然后:

     if (isNetworkEnabled) {
   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,10, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();


                    }
                }

关于android - 试图通过手机信号塔获取位置但仍返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46069293/

相关文章:

android - 添加可绘制资源

android:如何更改 ListView 中 row_item 的 layout_gravity 属性

java - 滚动 Pane 图像表

mobile - WiFi接入点的位置可以用以下数据进行三角测量吗?

algorithm - 数学 - 3d 定位/多点定位

android - 使用 Android.Xamarin 查找纬度和经度

android - Kotlin 使用 Gson 将 json 字符串转换为对象列表

android - 矩形 Canvas 中的效果阴影

java - 当设备缓慢移动或静止时 GPS 会波动

Android:GPS 从精细到粗糙的回退