在对话框中启用GPS后,Android位置返回null [英] Android Location return null after Enabling GPS in dialog

查看:138
本文介绍了在对话框中启用GPS后,Android位置返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我进入屏幕时,我检查GPS是否打开,如果没有,则显示启用GPS的对话框。当用户点击Yes时,onActivityResult - > GPS已打开,我尝试获取位置,但始终返回null



当我用GPS进入屏幕时,位置被正确地检索。我一直在为此奋斗几天,似乎无法找到任何资源。



UserLocationUtilities.java

  public class UserLocationUtilities实现GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {

GoogleApiClient googleApiClient;
活动活动;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;

boolean isGPSEnabled = false;
//网络状态标志
boolean isNetworkEnabled = false;
// GPS状态标志
boolean canGetLocation = false;

保护LocationManager locationManager;
protected LocationListener locationListener;
保护地点位置;
保护双纬度,经度;
protected boolean gps_enabled,network_enabled;

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10米
//以毫秒为单位的更新之间的最短时间
私有静态最终长MIN_TIME_BW_UPDATES = 1 * 1000 * 60; // 1分钟

公共UserLocationUtilities(活动活动){
this.activity =活动;

$ b $ public void settingsRequest()
{
if(googleApiClient == null){
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //这是关键成分

PendingResult< LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient,builder.build());
result.setResultCallback(new ResultCallback< LocationSettingsResult>(){
@Override
public void onResult(LocationSettingsResult result){
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch(status.getStatusCode()){
case LocationSettingsStatusCodes.SUCCESS:
//所有位置设置都满足客户端可以初始化位置
//在这里请求

break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
//位置设置不满足,但可以通过显示用户
//一个对话框
try {
//通过调用startResolut来显示对话框ionForResult(),
//并检查onActivityResult()中的结果。
status.startResolutionForResult(activity,REQUEST_CHECK_SETTINGS);
} catch(IntentSender.SendIntentException e){
//忽略错误。
}
break;
案例LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//位置设置不满意。但是,我们无法修复
//设置,所以我们不会显示对话框。
休息;
}
}
});

$ b public Location getLocation(){
if(ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
try {
locationManager =(LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);

isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供者
} else {
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(网络,网络);
if(locationManager!= null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();


$ b //如果启用GPS,使用GPS服务获得经纬度
if(isGPSEnabled){
if(location == null ){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch(Exception e){
e.printStackTrace();
}
}

返回地点;


public boolean isLocationEnabled(){
int locationMode = 0;
字符串locationProviders; (Build.VERSION.SDK_INT> = Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(activity.getApplicationContext()。getContentResolver (),Settings.Secure.LOCATION_MODE);

catch(Settings.SettingNotFoundException e){
e.printStackTrace();
}

return locationMode!= Settings.Secure.LOCATION_MODE_OFF;
$ b $ else} {
locationProviders = Settings.Secure.getString(activity.getApplicationContext()。getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return!TextUtils.isEmpty(locationProviders);
}


}

@Override
public void onConnected(Bundle bundle){




@Override
public void onConnectionSuspended(int i){

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult){

}

@Override
public void onLocationChanged(Location location){

}

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

}

@Override
public void onProviderEnabled (String provider){

}

@Override
public void onProviderDisabled(String provider){

}
}

用户在设置对话框中选择是,onActivityResult,我做了location = userlocationutilities.getLocation();并始终返回null。

  @Override 
public void onActivityResult(int requestCode,int resultCode ,意图数据){
switch(requestCode){
//检查最初提供给startResolutionForResult()的整数请求代码。
case REQUEST_CHECK_SETTINGS:
switch(resultCode){
case Activity.RESULT_OK://位置设置对话框,用户选择YES以启用位置
$ b $位置= userLocationUtilities.getLocation ();
if(location!= null){
//用户位置FOUND
Toast.makeText(getActivity(),Lat:+ location.getLatitude()+Long:+ location.getLongitude(),Toast.LENGTH_LONG).show();
getRingsNearMeCall();

} else {
//用户的位置NOT FOUND
Toast.makeText(getActivity(),null location,Toast.LENGTH_LONG).show();

}

break;
案例Activity.RESULT_CANCELED://位置设置对话框,用户选择NO启用位置
userLocationUtilities.settingsRequest(); //再次询问用户位置设置对话框
break;
}
break;






编辑:我在片段中做了requestPermission,授予权限

  if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ 
ActivityCompat.requestPermissions(getActivity(),new String [] {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ACCESS_FINE_LOCATION);
} else {
checkLocationSettingsGetRings();


解决方案

方法对我来说,它的工作很好 -

@Override
public void onLocationChanged(Location location){
getLocation(onLocationChanged);
}


When I enter a screen, I check for if GPS is turned on, if not, the dialog to enable GPS is shown. When user clicks Yes, onActivityResult -> GPS is turned on and I try to get the location but this always returns null

When I enter the screen with GPS already on, location is retrieved properly. I have been struggling with this for few days now and can't seem to find any resources.

UserLocationUtilities.java

public class UserLocationUtilities implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    GoogleApiClient googleApiClient;
    Activity activity;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;

    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Location location;
    protected double latitude,longitude;
    protected boolean gps_enabled,network_enabled;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1 * 1000 * 60; // 1 minute

    public UserLocationUtilities(Activity activity){
        this.activity = activity;
    }

    public void settingsRequest()
    {
        if(googleApiClient == null){
            googleApiClient = new GoogleApiClient.Builder(activity)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            googleApiClient.connect();
        }

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }

    public Location getLocation() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            try {
                locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return location;
    }

    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            try {
                locationMode = Settings.Secure.getInt(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE);

            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }

            return locationMode != Settings.Secure.LOCATION_MODE_OFF;

        }else{
            locationProviders = Settings.Secure.getString(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }


    }

    @Override
    public void onConnected(Bundle bundle) {


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

After user selects Yes in Settings Dialog, onActivityResult, I do location = userlocationutilities.getLocation(); and always returns null. If switch screens and come back, location is retrieved.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK: //location settings dialog, user selected YES to enabling location

                        location = userLocationUtilities.getLocation();
                        if(location != null){
                            //location of user FOUND
                            Toast.makeText(getActivity(), "Lat: "+location.getLatitude()+" Long: "+location.getLongitude(), Toast.LENGTH_LONG).show();
                            getRingsNearMeCall();

                        }else{
                            //location of user NOT FOUND
                            Toast.makeText(getActivity(), "null location", Toast.LENGTH_LONG).show();

                        }

                        break;
                    case Activity.RESULT_CANCELED: //location settings dialog, user selected NO to enabling location
                        userLocationUtilities.settingsRequest(); //ask user again with Location Settings Dialog
                        break;
                }
                break;
        }
    }

Editted: I make the requestPermission in the fragment, the permission is granted

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION },
                    PERMISSION_ACCESS_FINE_LOCATION);
        }else{
            checkLocationSettingsGetRings();
        }

解决方案

Add this override method for me its worked fine--

@Override public void onLocationChanged(Location location) { getLocation("onLocationChanged"); }

这篇关于在对话框中启用GPS后,Android位置返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆