java - 为什么我的位置在第一次尝试时返回 null?

标签 java android location

当我第一次安装我的应用程序时,它总是返回空位置,但如果任何其他应用程序使用位置,那么我重新运行该应用程序,然后我的应用程序可以获取我的位置地址。如何在第一次运行时成功更新位置?

//这是我的代码

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) {

    }
}

最佳答案

此链接可能对您有帮助 http://shaoniiuc.com/android/android-receiving-location-updates-kotlin/

我假设您的 list 中已经有COARSEFINE 位置

或者类似这样的内容:

    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);
        }
    }
}

从任何方法调用它。

来源:https://stackoverflow.com/a/9873478/13319579

关于java - 为什么我的位置在第一次尝试时返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61458611/

相关文章:

java - 可点击的项目形成 ListView : setOnItemClickListener won't work

java - 从 Spring 应用程序中的 jar 中读取 log4j.xml

android - 定期获取位置并绘制标记以映射

java - android studio 与 Java 编译器错误 : string too large to encode using UTF-8 written instead as 'STRING_TOO_LARGE'

location - Android - 地理围栏不起作用,使用 coarse_location

c# - 将鼠标点击发送到另一个应用程序的 X Y 坐标

java - 如何使用 Mockito 模拟方法调用

java - 从数据模型访问同级数据

java - Android DrawerLayout 未关闭

android - 在自定义 View 上设置内部 edittext xml 属性