Не могу получить разрешение на местоположение для Marshmallow os

Я пытался заставить мое местоположение приложения работать с новым форматом зефира, но получал нуль и не мог понять это, так как это доставляло мне много головной боли в течение нескольких дней. Это мой текущий класс службы определения местоположения

public class GPSService extends Service implements LocationListener {

// saving the context for later use
private final Context mContext;

// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 300;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
    this.mContext = context;
    mLocationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

}


public Location getLocation() {
    try {

        // Getting GPS status
        isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // If GPS enabled, get latitude/longitude using GPS Services
        if (isGPSEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                    // location is available
                    return mLocation;
                }
            }
        }

        // If we are reaching this part, it means GPS was not able to fetch
        // any location
        // Getting network status
        isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                    // location is available
                    return mLocation;
                }
            }
        }
        // If reaching here means, we were not able to get location neither
        // from GPS not Network,
        if (!isGPSEnabled) {
            // so asking user to open GPS
            askUserToOpenGPS();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    // if reaching here means, location was not available, so setting the
    // flag as false
    isLocationAvailable = false;
    return null;
}

/**
 * Gives you complete address of the location
 *
 * @return complete address in String
 */
public String getLocationAddress() {

    if (isLocationAvailable) {

        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
            /*
             * Return 1 address.
             */
            addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
            return ("IO Exception trying to get address:" + e1);
        } catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments "
                    + Double.toString(mLatitude) + " , "
                    + Double.toString(mLongitude)
                    + " passed to address service";
            e2.printStackTrace();
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            /*
             * Format the first line of address (if available), city, and
             * country name.
             */
            String addressText = String.format(
                    "%s, %s, %s,%s",
                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",
                    // Locality is usually a city
                    address.getLocality(),
                    address.getAdminArea(),
                    // The country of the address
                    address.getCountryName());
            // Return the text
            return addressText;
        } else {
            return getString(R.string.no_address_gpsservice);
        }
    } else {
        return getString(R.string.loc_unavaliable);
    }

}



/**
 * get latitude
 *
 * @return latitude in double
 */
public double getLatitude() {
    if (mLocation != null) {
        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * get longitude
 *
 * @return longitude in double
 */
public double getLongitude() {
    if (mLocation != null) {
        mLongitude = mLocation.getLongitude();
    }
    return mLongitude;
}

/**
 * close GPS to save battery
 */
public void closeGPS() {

    if (mLocationManager != null) {
        mLocationManager.removeUpdates(GPSService.this);
    }
}

/**
 * show settings to open GPS
 */
public void askUserToOpenGPS() {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    mAlertDialog.setTitle(R.string.gpsservice_dialog_title)
            .setMessage(R.string.gpsservice_dialog_message)
            .setPositiveButton(R.string.gpsservice_dialog_positive, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            })
            .setNegativeButton(R.string.gpsservice_dialog_negative,new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).show();
}

/**
 * Updating the location when location changes
 */
@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

person Clara Raymond    schedule 29.08.2016    source источник
comment
это какая-либо ошибка в вашем логарифме, и вы запросили разрешения в своем манифесте и в коде. Вы знаете, что у зефира есть новый способ обработки разрешений.   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
это новый способ, я не понимаю, прочитал много ответов на него, но я не понимаю, применил его так же, как они, но я получаю ноль @MueyiwaMosesIkomi   -  person Clara Raymond    schedule 29.08.2016
comment
ваш вопрос был дублирован как дубликат, поэтому я не смогу опубликовать ответ, но вы уверены, что ваш GPS выбирает местоположения. Проверьте с другим приложением GPS. Если у вас есть показания, попробуйте ваше приложение. GPS может быть трудно получить в некоторых областях.   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
GPS в настоящее время работает для других версий, мне просто нужно настроить его для зефира @MueyiwaMosesIkomi   -  person Clara Raymond    schedule 29.08.2016
comment
позвольте мне рассказать, как я получаю свои разрешения в mashmallow...   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
частный статический окончательный int PERMS_REQUEST_CODE = 123;   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
//Обработка разрешений private boolean hasPermissions(){ int res = 0; String [] разрешения = новая строка [] {android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.READ_SMS}; for(String perms: разрешения) { res = checkCallingOrSelfPermission(perms); if(!(res == PackageManager.PERMISSION_GRANTED)){ вернуть ложь; } } вернуть истину; }   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
private void requestPerms () {String [] разрешения = новая строка [] {android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.READ_SMS}; if(Build.VERSION.SDK_INT ›= Build.VERSION_CODES.M){ requestPermissions(разрешения, PERMS_REQUEST_CODE); } }   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
вам нужно запросить разрешение во время выполнения, что объясняется в другом вопросе, который мы пометили как дубликат, и в документации по Android developer.android.com/training/permissions/requesting.html   -  person tyczj    schedule 29.08.2016
comment
есть onRequestPermissions ... но слишком долго для комментариев. Получаете ли вы разрешения на всплывающие окна при запуске приложения во время выполнения?   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
процесс запроса разрешения, когда он ломается   -  person Clara Raymond    schedule 29.08.2016
comment
и вы уверены, что у вас также есть это разрешение в вашем манифесте. Где я могу опубликовать вам полный код?   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016
comment
можно закинуть в блокнот и отправить по почте большое спасибо. у меня есть разрешение в манифесте.   -  person Clara Raymond    schedule 29.08.2016
comment
[email protected]   -  person Clara Raymond    schedule 29.08.2016
comment
отправил, надеюсь поможет...   -  person Mueyiwa Moses Ikomi    schedule 29.08.2016