java - 位置管理器检查权限

标签 java android locationmanager android-gps

所以我的问题非常简单,我不知道如何在这段代码中实现 checkPermission 。我已经阅读过它,但我仍然无法完全理解它。我的问题之一是有些例子希望我指出一项 Activity ,但这不起作用。

我请求位置更新的行抛出 SecurityException 并要求我执行 checkPermission。

代码示例和/或解释会让我非常感激。

如果我的解释不够,请提前原谅,我在这方面很糟糕!

public class LocationHandler implements LocationListener {
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// 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 = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager mLocationManager;

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

    //Check Permission
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        MIN_TIME_BW_UPDATES,
        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}

@Override
public void onLocationChanged(Location location) {

    String msg = "New Latitude: " + location.getLatitude()
            + "New Longitude: " + location.getLongitude();

    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();

}

@Override
public void onProviderDisabled(String provider) {

    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    mContext.startActivity(intent);
    Toast.makeText(mContext, "Gps is turned off!! ",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {

    Toast.makeText(mContext, "Gps is turned on!! ",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

最佳答案

这里是一些可能有帮助的代码。

您需要使用 try/catch 包装位置请求以防止安全异常。

添加到 strings.xml:

<string name="location_permission_rationale">"Location permission is needed for providing nearby services."</string>

导入此:

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

您的 Activity 类和 LocationHandler 中需要

/**
 * Id to identity LOCATION permission request.
 */
private static final int REQUEST_LOCATION = 0; 

...

在您的 Activity 类中覆盖:

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_LOCATION) {
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // You can request location here and update your vars
        }
    }
}

将其添加到您的 LocationHandler 类并从构造函数中调用。如果它返回true,那么你就是gtg。如果它返回 false,那么您必须在回调中进行位置更新。

private boolean requestLocationPermission() {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(mContext, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }

    if (shouldShowRequestPermissionRationale((Activity)mContext, ACCESS_FINE_LOCATION)) {

        Snackbar.make(((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content),
                ((Activity)mContext).getResources().getString(R.string.location_permission_rationale), Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions((Activity)mContext, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
                    }
                });
    } else {
        requestPermissions((Activity)mContext, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
    }
    return false;
}

关于java - 位置管理器检查权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44160127/

相关文章:

java - 带进度条的 AsyncTask

java - android - 仅当条件为真时获取位置并将数据发送到远程服务器

java - 如何通过反射运行挂起方法?

java - 在字符串中每一个或两个字符后插入空格

java - EntityManager 嵌套事务原子性

java - 如何在随后打印的质因数之间添加 "x"而在最后打印的质因数之后没有额外的 "x"?

android - 向 Android 项目添加 libjitsi 依赖是否可行?

android - 如何使用 appcompat v21 在独立工具栏上启用 homeAsUp 或调用 setDisplayHomeAsUpEnabled()

Android 服务在重启时不保留数据

android - android 多久请求一次位置更新?