【问题标题】:LocationManager checkPermission位置管理器检查权限
【发布时间】:2017-05-24 13:40:57
【问题描述】:

所以我的问题很简单,我不知道如何在这段代码中实现 checkPermission。我已经阅读了它,但我仍然无法完全理解它。我的一个问题是,一些示例希望我指向一项活动,但这不起作用。

我请求位置更新的行抛出 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

}
}

【问题讨论】:

    标签: java android locationmanager android-gps


    【解决方案1】:

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

    您需要使用 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;
    

    在您的活动类和 LocationHandler 中需要

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

    ...

    在您的活动类中覆盖:

    /**
     * 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;
    }
    

    【讨论】:

    • onRequestPermissionsResult 没有覆盖,我需要实现其他东西吗?我也无法让“ACCESS_FINE_LOCATION”工作。尝试指向清单,但也没有用。
    • 对于 ACCESS_FINE_LOCATION 请将其添加到您的导入中: import static android.Manifest.permission.ACCESS_FINE_LOCATION;要覆盖 onRequestPermissionsResult,您需要有权访问扩展 AppCompatActivity 的活动。您能以某种方式为您的班级提供活动参考吗?
    • 添加该导入后仍有错误:ContextCompat 中的 checkSelfPermission (android.content.Context, String) 无法应用于 (java.lang.String)。如果那是您的意思的引用,我已经从其他活动中获得了上下文,但是我如何将其应用于覆盖方法?
    • 您需要将您的活动上下文添加到requestPermissions,第一个参数。 void requestPermissions(活动活动,String[] 权限,int requestCode)。给我一秒钟弄清楚 checkSelfPermission 出了什么问题。
    • 顺便说一下,尝试将您的活动上下文也添加到 checkSelfPermission 中。作为第一个参数:int checkSelfPermission(上下文上下文,字符串权限)
    【解决方案2】:

    您似乎忘记在清单中添加这两个权限。

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    

    【讨论】:

    • 请张贴您的日志,它可能对一些细节有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 2015-12-19
    • 2019-03-27
    • 2016-12-08
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多