FusedLocationAPI在添加权限后第一次返回null

时间:2017-09-15 08:54:09

标签: android android-permissions android-fusedlocation

我正在我的应用中实现fusedLocationAPI。对于带> = Marshmallow的Android手机,我正在添加权限。问题是安装后第一次将lat和long值返回为null。但是下次启动应用程序后,它运行正常。下面我发布我的代码。请看看。

在onCreate()中:

     manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        buildGoogleApiClient();
        checkPermission();
        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
        }
        if (!statusOfGPS) {
            displayPromptForEnablingGPS(MainActivity.this);
        }

其他方法:

      @Override
    public void onConnected(@Nullable Bundle bundle) {
        checkPermission();
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Update location every second

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null) {
                lat = mLastLocation.getLatitude();
                lon = mLastLocation.getLongitude();
                if (!String.valueOf(lat).equals("0.0")){
                    latitudeVal = mLastLocation.getLatitude();
                    longitudeVal = mLastLocation.getLongitude();
                    Log.e("Lat and Lng", String.valueOf(latitudeVal)+ longitudeVal);
                }
            }

        }

        @Override
        public void onConnectionSuspended(int i) {

        }
        synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        }
        public void displayPromptForEnablingGPS(final Activity activity) {
            final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
            final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
            final String message = "Do you want open GPS setting?";
            builder.setMessage(message)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface d, int id) {
                                    activity.startActivity(new Intent(action));
                                    d.dismiss();
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface d, int id) {
                                    d.cancel();
                                }
                            });
            builder.create().show();
        }

    private void requestPermission() {

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };


    Activity activity =this;
    Context context = this;


    private  boolean checkPermission() {
        int result;
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String p:permissions) {
            result = ContextCompat.checkSelfPermission(this,p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),10 );

            Log.d("permissionissue","no");
            return false;
        }
        Log.d("permissionissue","yes");
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 101:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
                    checkPermission();
                } else {
                    Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();

                    try {
                        Log.d("deniedOnes",permissions[0] + " Denied!!!");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

2 个答案:

答案 0 :(得分:0)

请使用此代码:

//变量声明

  final int MY_REQUEST_CODE=20;

//询问权限的方法

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
        } else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
           // do your Task here 
        }
    } else {
        // do your Task here

    }

现在permissionResult写下这个:

@Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
            // do your Task here 
        } else {
            Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
        }
    }

答案 1 :(得分:0)

如果FusedLocationProviderClient的位置为空,请尝试使用LocationManager获取位置更新。对于Eg:

mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {

            if (location == null) {
                startGPS();
            } else {
                startIntentService(location);
            }
        }
    });

public void startGPS(){

    mLocationManager = (LocationManager)SmileMore.appContext.getSystemService(LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
}

private void initLocationListener(){

    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            if(location == null){
                return;
            }
            mLocationManager.removeUpdates(this); // remove this listener as soon as you get first location update.
            startIntentService(location);
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
}