【问题标题】:current location is always null当前位置始终为空
【发布时间】:2011-08-09 10:41:45
【问题描述】:

我正在尝试使用 gps 或网络在编辑框中单击按钮来检索我当前的位置..我已经尝试了我在教程和旧帖子中找到的所有可能的方法..但是我的位置始终为空.. 我没有明白我错在哪里。? 我正在有网络但没有互联网/gprs 的真实设备上对其进行测试...

这是我正在使用的代码..我也尝试了与 GPS_PROVIDER 相同的代码..请帮助我..

     protected void showCurrentLocation() 
   {
     geocoder = new Geocoder(this); 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
     locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );

   Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
   System.out.println("loc.."+location);
   if (location != null) 
   {
   String message = String.format("Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());
       Toast.makeText(ShowActivity.this, message,
               Toast.LENGTH_LONG).show();
  //acTextView.setText(message);
   try {
          List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
          for (Address address : addresses) {
              System.out.println("my location .."+address.getAddressLine(0));
            acTextView.setText(address.getAddressLine(0));
          }



        } catch (IOException e) {
          Log.e("LocateMe", "Could not get Geocoder data", e);
        }
    }
    else
    {
    AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
    alertbox1.setMessage("No GPS or network ..Signal please fill the location manually!");
    alertbox1.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) 
    {}});
    alertbox1.show();
    }

}   

我只是在编辑问题而不是问新问题..因为我的问题仍然与相同的问题有关...我没有更改代码中的任何内容,现在它工作得很好.....但问题是当我使用 GPS_PROVIDER 时,它会返回准确的地址以及经度和纬度的值。但是当我使用 NETWORK_PROVIDER 时,它只返回经度和纬度的值,没有地址……我想检索完整的使用 NETWORK_PROVIDER 的地址,因为 GPS 不能在室内工作......我该怎么做?

谢谢...!!

【问题讨论】:

  • 你在模拟器上运行代码吗???那么你在 lastKnownLocaton 中总是会得到 null ......所以从开始尝试默认值或使用共享首选项。
  • no..我在问题中提到“我正在有网络但没有互联网/gprs的真实设备上测试它......”
  • Jainal 回答后你还有问题吗??
  • 是的..我已经添加了所有必需的权限..
  • 你能告诉我为什么我的 gps 的 getLastKnownLocation 总是返回 null 吗?你有没有得到任何解决方案?请回复我是否自 3 周以来一直被此问题困扰。

标签: android geolocation geocoding locationmanager


【解决方案1】:

请检查您的清单文件。您是否添加了这些权限。

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

查看更新后的答案:

protected void showCurrentLocation() 
       {
         geocoder = new Geocoder(this); 
         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 
                    MINIMUM_TIME_BETWEEN_UPDATES, 
                    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                    myLocationListener
            );
         timer = new Timer();
         timer.schedule(new GetLastLocation(),20000);

       }

     class GetLastLocation extends TimerTask {

            @Override
            public void run() {
                timer.cancel();
                locationManager.removeUpdates(locationListener);
                 Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                   System.out.println("loc.."+location);
                   if (location != null) 
                   {
                   String message = String.format("Location \n Longitude: %1$s \n Latitude: %2$s",
                                location.getLongitude(), location.getLatitude());
                       Toast.makeText(ShowActivity.this, message,
                               Toast.LENGTH_LONG).show();
                  //acTextView.setText(message);
                   try {
                          List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
                          for (Address address : addresses) {
                              System.out.println("my location .."+address.getAddressLine(0));
                            acTextView.setText(address.getAddressLine(0));
                          }



                        } catch (IOException e) {
                          Log.e("LocateMe", "Could not get Geocoder data", e);
                        }
                    }
                    else
                    {
                    AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
                    alertbox1.setMessage("No GPS or network ..Signal please fill the location manually!");
                    alertbox1.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) 
                    {}});
                    alertbox1.show();
                    }
                }   
                return;
            }
        }

     /** The location listener. */
        LocationListener myLocationListener = new LocationListener() {

            public void onLocationChanged(Location location) {

            }
            public void onProviderDisabled(String provider) {}
            public void onProviderEnabled(String provider) {}
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        };

【讨论】:

    【解决方案2】:

    locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 获得空值的另一个原因是您的网络提供商已关闭。在我的手机上,这是通过设置 -> 位置 -> 使用无线网络来切换的。

    编辑:

    你也可以试试:

    LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    

    查看网络提供商是否启用或

    LocationManager.getProviders(true)
    

    返回任何已启用的提供程序。

    更多信息请见http://developer.android.com/reference/android/location/LocationManager.htm

    【讨论】:

    • @jiya - 您需要从代码中取出 System.out.println 语句。 Android 中没有控制台。替换为 Log.d(...)。此外,尝试将 MINIMUM_TIME_BETWEEN_UPDATES 设置为 0 并在您的位置侦听器中放置一条日志语句,以查看在确实启用了网络提供商时触发位置更新时会发生什么。例如。您的手机可能从未请求过任何位置,这意味着在创建之前它始终为空。
    【解决方案3】:

    Android 2.3.x SDK(API 9 和 10)模拟器存在 GPS 错误。您应该在 2.2 (API 8) 上尝试您的代码

    【讨论】:

    【解决方案4】:

    当我们指定 NETWORK_PROVIDER 来监听位置更新时,

    Android 系统使用 wi-fi id 或互联网接入点来确定位置

    没有网络时,返回空值

    我也遇到过,它没有像预期的那样从手机信号塔获取位置

    阅读:no gprs/no wi-fi location updates

    【讨论】:

      【解决方案5】:

      试试这个代码:

      public CurrentLocation(Context ctx) {
          this.context = ctx;
      
          locationManager = (LocationManager) context
                  .getSystemService(Context.LOCATION_SERVICE);
          @SuppressWarnings("unused")
          List<String> providers = locationManager.getAllProviders();
      
          Criteria locationCritera = new Criteria();
          String providerName = locationManager.getBestProvider(locationCritera,
                  true);
      
          location = locationManager.getLastKnownLocation(providerName);
          locationListener = new MyLocationListener();
      
          locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                  0, locationListener);
      
      
      
      }
      

      【讨论】:

      • 谢谢hanry..但这在我的情况下不起作用..这段代码给出了空指针异常......
      【解决方案6】:

      使用此代码

      if (android.os.Build.VERSION.SDK_INT > 8) {
      
              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
              StrictMode.setThreadPolicy(policy);
      
          }
      

      还要检查您的设置 --> 位置和安全性 --> 是否启用了使用无线网络。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多