current location is always null

后端 未结 6 1867
独厮守ぢ
独厮守ぢ 2021-02-04 22:39

I am trying to retrieve my current location on the button click in an editbox using gps or network..i have tried all possible methods which i found in tutorials and older posts.

相关标签:
6条回答
  • 2021-02-04 22:56

    Try this Code:

    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);
    
    
    
    }
    
    0 讨论(0)
  • 2021-02-04 22:58

    Another reason for getting null back from locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); would be if your network provider was turned off. On my phone this is toggled via Settings -> Location -> Use wireless networks.

    EDIT:

    You could also try:

    LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    

    to see if the network provider is enabled or

    LocationManager.getProviders(true)
    

    to return any enabled providers.

    See http://developer.android.com/reference/android/location/LocationManager.htm for more info

    0 讨论(0)
  • 2021-02-04 22:59

    pleas check your manifest file.whether have you added those permissions or not.

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

    See the updated answer:

    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) {}
            };
    
    0 讨论(0)
  • 2021-02-04 22:59

    Android 2.3.x SDK (API 9 and 10) emulator has bug with GPS. You should try your code on 2.2 (API 8)

    0 讨论(0)
  • 2021-02-04 23:09

    when we specify NETWORK_PROVIDER to listen for location updates,

    Android system makes use of wi-fi ids or internet access points to determine locations

    When there is no internet access, it returns null values

    Happened with me too, it doesnt get location from cell towers as expected

    read into this: no gprs/no wi-fi location updates

    0 讨论(0)
  • 2021-02-04 23:09

    Use this code

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

    And also check your Settings --> Location and security --> Use wireless networks is enabled or not.

    0 讨论(0)
提交回复
热议问题