Java 已在清单中添加权限,但访问被拒绝
我创建了类GPSTracker.java,以便为我当前的LatLng干杯。在清单中设置我的权限,但isNetworkEnabled在GPSTracker.java中仍显示为红色,并引发SecurityException:“网络”位置提供程序需要访问\u粗略\u位置或访问\u精细\u位置权限。谁能告诉我怎么解决这个问题吗。我已经尝试了我能想到的一切。 下面是GPSTracker.java的代码:Java 已在清单中添加权限,但访问被拒绝,java,android,Java,Android,我创建了类GPSTracker.java,以便为我当前的LatLng干杯。在清单中设置我的权限,但isNetworkEnabled在GPSTracker.java中仍显示为红色,并引发SecurityException:“网络”位置提供程序需要访问\u粗略\u位置或访问\u精细\u位置权限。谁能告诉我怎么解决这个问题吗。我已经尝试了我能想到的一切。 下面是GPSTracker.java的代码: public class GPSTracker extends Service implements
public class GPSTracker extends Service implements LocationListener{
private final Context context;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(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);
}
if(locationManager !=null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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 void stopUsingGPS() {
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onLocationChanged(Location arg0) {
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
下面是NewCatch.java上按钮的代码
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
sqLiteHelper.insertData(
edtSpecies.getText().toString().trim(),
edtDate.getText().toString().trim(),
edtWeight.getText().toString().trim(),
edtLength.getText().toString().trim(),
edtSex.getText().toString().trim(),
edtBait.getText().toString().trim(),
edtMethod.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Entry Added", Toast.LENGTH_LONG).show();
edtSpecies.setText("");
edtDate.setText("");
edtWeight.setText("");
edtLength.setText("");
edtSex.setText("");
edtBait.setText("");
edtMethod.setText("");
imageView.setImageResource(R.drawable.fishing);
}
catch(Exception e)
{
e.printStackTrace();
}
//////
gps = new GPSTracker(NewCatch.this);
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Location Saved -\nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG);
}
else {
gps.showSettingsAlert();
}
//////
}
});
最后但并非最不重要的是我的清单:
<?xml version="1.0" encoding="utf-8"?>
<!--suppress AndroidDomInspection -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="devsolutionsbeyond.media.fishinglog">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Dash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewCatch" />
<activity android:name=".About" />
<activity android:name=".FishList" />
<activity android:name=".Maps"
android:label="@string/title_activity_maps" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.Fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<service android:name=".GPSTracker" />
</application>
在更高的Android版本(Android 6.0(API级别23)或更高)中,某些权限被标记为危险 虽然您可以在清单中提到它们,并且对于使用较旧Android版本的用户来说已经足够了,但是您仍然需要在运行时询问用户(对于更高版本的用户)!系统将使用对话框询问用户。“(你的应用程序名)想要访问你的位置”,用户将选择允许或不允许,你将处理逻辑
在更高的Android版本(Android 6.0(API级别23)或更高版本)中,某些权限被标记为危险 虽然您可以在清单中提到它们,并且对于使用较旧Android版本的用户来说已经足够了,但是您仍然需要在运行时询问用户(对于更高版本的用户)!系统将使用对话框询问用户。“(你的应用程序名)想要访问你的位置”,用户将选择允许或不允许,你将处理逻辑
您可以查看相应的权限。检查权限,如果未找到,请请求权限,如下所示:
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1600);
}
您可以得到如下结果:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],@NonNull int[] grantResults) {
if(requestCode==REQUESTID){
// If request is cancelled, the result arrays are empty.
if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was not granted, boo!
//show the permission rationale if the user did not click never show again
if(ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this,android.Manifest.permission.ACCESS_FINE_LOCATION)){
//means user did not choose to never show permissions again. show the alert dialog
//Show a message explaining why the permission is necessary
//This explanation will only be shown if the user hasn't clicked do not show again on the permission dialog
}
}
}
}
和往常一样,将您的位置请求调用包含在try-catch块中,因为用户总是可以拒绝权限,这将导致崩溃
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (SecurityException se) {
Toast.makeText(this, "Please provide location permissions to continue", Toast.LENGTH_SHORT).show();
}
检查权限,如果未找到,请请求权限,如下所示:
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1600);
}
您可以得到如下结果:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],@NonNull int[] grantResults) {
if(requestCode==REQUESTID){
// If request is cancelled, the result arrays are empty.
if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was not granted, boo!
//show the permission rationale if the user did not click never show again
if(ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this,android.Manifest.permission.ACCESS_FINE_LOCATION)){
//means user did not choose to never show permissions again. show the alert dialog
//Show a message explaining why the permission is necessary
//This explanation will only be shown if the user hasn't clicked do not show again on the permission dialog
}
}
}
}
和往常一样,将您的位置请求调用包含在try-catch块中,因为用户总是可以拒绝权限,这将导致崩溃
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (SecurityException se) {
Toast.makeText(this, "Please provide location permissions to continue", Toast.LENGTH_SHORT).show();
}
在服务内部的代码中添加这一行
boolean isNetworkEnabled= false;
并为安全异常相关问题添加所需的权限。在服务内部的代码中添加这一行
boolean isNetworkEnabled= false;
并为安全异常相关问题添加所需的权限。首先,您需要请求运行时权限。第二,这个类是可怕的破坏,永远不应该使用。请参阅为什么它的解决方案不完善和更好。isNetworkEnabled()可能重复;是一个返回布尔值true或false的自定义函数。让您的功能检查移动数据或wifi是否打开或关闭,并相应地返回true false和false,然后执行您的操作。首先,您需要请求运行时许可。第二,这个类是可怕的破坏,永远不应该使用。请参阅为什么它的解决方案不完善和更好。isNetworkEnabled()可能重复;是一个返回布尔值true或false的自定义函数。让您的功能检查移动数据或wifi是否打开或关闭,并相应地返回true false,然后执行您的操作。好的,我已编辑,但我想首先检查您是否尝试在较旧的android设备@Devsolutionsbeyond中运行您的应用程序,如果您可以访问?我想确保这是您的程序中唯一的错误,然后再解决它!此外,isNetworkEnabled无法解析符号…牛轧糖和马什梅洛中的同一事物sry Marshamallow和牛轧糖均为23及以上!你需要棒棒糖或更少!好的,我已经编辑过了,但我想先看看你是否尝试在旧的android设备@Devsolutionsbeyond上运行你的应用程序,如果你可以访问?在解决它之前,我想确保这是你程序中唯一的一个错误!此外,isNetworkEnabled无法解析符号…牛轧糖和马什梅洛中的同一事物sry Marshamallow和牛轧糖均为23及以上!你需要棒棒糖或更少!这里是仅使用精细位置,您将粗略位置添加到列表中,并检查结果内部,而不是我使用的硬编码0索引。这里是仅使用精细位置,您将粗略位置添加到列表中,并检查结果内部,而不是我使用的硬编码0索引