Почему мое местоположение возвращает нулевое значение с первой попытки? - PullRequest
0 голосов
/ 27 апреля 2020

Когда я устанавливаю свое приложение в первый раз, оно всегда возвращает нулевое местоположение, но если любое другое приложение использует местоположение, то я перезапускаю приложение, и мое приложение может получить мой адрес местоположения. Как успешно обновить местоположение с первого запуска?

// вот мой код

public class UserinfoActivity extends AppCompatActivity implements LocationListener {

    private Button button;
    private EditText editText_pin, editText_mobile, editText_address;
    DatabaseReference databaseReference;
    MyPreferences myPreferences;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;
    Location currentLocation;

    Intent intentThatCalled;
    public double latitude;
    public double longitude;
    public LocationManager locationManager;
    public Criteria criteria;
    public String bestProvider;

      @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        databaseReference = FirebaseDatabase.getInstance().getReference("user_responses");
        myPreferences = MyPreferences.getPreferences(this);

        fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);

        intentThatCalled = getIntent();
        getLocation();

          //optional_check
            if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

                ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                        REQUEST_CODE);
            }
            Task<Location> task=fusedLocationProviderClient.getLastLocation();
            task.addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if(location!=null){
                        currentLocation=location;
                    }
                }
            });

                public static boolean isLocationEnabled(Context context) {
        //...............
        return true;
    }

    protected void getLocation() {
        if (isLocationEnabled(UserinfoActivity.this)) {
            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            criteria = new Criteria();
            bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();

            //You can still do this if you like, you might get lucky:
            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;
            }
            Location location = locationManager.getLastKnownLocation(bestProvider);
            if (location != null) {
                Log.e("TAG", "GPS is on");
                Double latitude = location.getLatitude();
                float float_latitude = latitude.floatValue();
                myPreferences.setlatitude(float_latitude);

                Double longitude = location.getLongitude();
                float float_longitude = longitude.floatValue();
                myPreferences.setlongitude(float_longitude);


                /*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
                searchNearestPlace(voice2text);*/
            }
            else{
                //This is what you need:
                locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
            }
        }
        else
        {
            //prompt user to enable location....
            //.................
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);

    }
    @Override
    public void onLocationChanged(Location location) {

        locationManager.removeUpdates(this);

        //open the map:
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        /*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
        searchNearestPlace(voice2text);*/
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

1 Ответ

0 голосов
/ 27 апреля 2020

Эта ссылка может помочь вам http://shaoniiuc.com/android/android-receiving-location-updates-kotlin/

Я предполагаю, что у вас уже есть COARSE и FINE местоположений в вашем манифесте

Или что-то еще как это:

    Log.d("Find Location", "in find_location");
    this.con = con;
    String location_context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) con.getSystemService(location_context);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 1000, 0,
            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) {}
            });
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            addr = ConvertPointToLocation(latitude, longitude);
            String temp_c = SendToUrl(addr);
        }
    }
}

Вызовите это из любого метода.

Источник: { ссылка }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...