在android中获得运行时权限

Posted

技术标签:

【中文标题】在android中获得运行时权限【英文标题】:Getting permission on runtime in android 【发布时间】:2018-05-25 05:26:40 【问题描述】:

我是android新手,不知道我做错了什么 这个班级得到经度和纬度并发送到另一个班级 代码抛出错误onrequstpermission 请告诉我该怎么做怎么做:

public void onRequestPermissionsResult(int requestCode, String[] 权限, int[] grantResults 上的错误

public class GPSTracker extends Service implements LocationListener 

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
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 locationManager;

public GPSTracker(Context context) 
    this.mContext = context;
    getLocation();


public Location getLocation() 
    try 
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) 
            // no network provider is enabled
         else 
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) 
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
                    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
                        switch (requestCode) 
                            case Manifest.permission.ACCESS_COARSE_LOCATION:
                                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                                    // All good!
                                 else 
                                    Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
                                

                                break;
                        
                    
                
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) 
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) 
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    
                
            
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) 
                if (location == null) 
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    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;


/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS()
    if(locationManager != null)
        locationManager.removeUpdates(GPSTracker.this);
    


/**
 * Function to get latitude
 * */
public double getLatitude()
    if(location != null)
        latitude = location.getLatitude();
    

    // return latitude
    return latitude;


/**
 * Function to get longitude
 * */
public double getLongitude()
    if(location != null)
        longitude = location.getLongitude();
    

    // return longitude
    return longitude;


/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() 
    return this.canGetLocation;


/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert()
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
        public void onClick(DialogInterface dialog,int which) 
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        
    );

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        public void onClick(DialogInterface dialog, int which) 
            dialog.cancel();
        
    );

    // Showing Alert Message
    alertDialog.show();


@Override
public void onLocationChanged(Location location) 


@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;

【问题讨论】:

你不能在另一个函数中声明一个函数 你可能会发现这个谈话很有帮助:youtu.be/WGz-alwVh8A 此外,这个帮助库使处理权限变得更加容易:github.com/hiqes/andele 【参考方案1】:

onRequestPermissionsResult 是一个应该在当前方法之外的方法

public Location getLocation()
    //...code
      if (ActivityCompat.checkSelfPermissio... ) 

    // ERROR : cannot have function declaration inside another function
          public void onRequestPermissionsResult(...) 
                switch (requestCode) //..code
          

注意:你不能在 Service 类中拥有这个,你需要一些 Activity 来请求许可

ActivityCompat.OnRequestPermissionsResultCallbackFragmentActivity 实现,它是AppCompatActivity 的父级,所以它不是由Service 实现的,因此您需要实现运行时权限代码是一些FragmentActivity | AppCompatActivity 或者您可以检查并显示通知(如果没有权限或可能是对话框)并将用户重定向到Activity 以继续使用权限代码。

参考: Implement runtime permission

【讨论】:

你能不能给个干净的代码,这个应用是marshmallo的 @AliAhmedSiddiqui 阅读更新后的答案,长话短说,您需要在某些活动中征求许可 等我查一下 案例公共类请求错误 public void onRequestPermissionsResult(int requestCode, String[] 权限, int[] grantResults) switch (requestCode) case Manifest.permission.ACCESS_FINE_LOCATION; if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) // 很好! else Toast.makeText(getApplicationContext(), "需要你的位置!", Toast.LENGTH_SHORT).show(); 休息; @AliAhmedSiddiqui 首先不要在评论中发布大量代码,看起来真的很难看,应该是 requst extends AppCompatActivity 而不是普通的 classonRequestPermissionsResult method 需要是 @987654337 @ ,希望你知道@Override 方法,你需要一些AppCompatActivity ,刷新页面以防你看不到更新并仔细按照说明进行

以上是关于在android中获得运行时权限的主要内容,如果未能解决你的问题,请参考以下文章

Android运行时权限即使没有权限也会通过

Android应用申请运行时权限(Permission)示例

如何在Android中询问Camera的运行时权限,运行时存储权限

融合位置 API 运行时权限错误

Android 运行时权限

运行时权限