Android 6.0 동적 액세스 권한 위치

7353 단어
Android6.0 이상 핸드폰은 일부 권한을 획득할 때 23 이하의 기종과 달리 안드로이드 마니파스트 파일에서 설정하면 됩니다. 만약에 targetSdkVersion>23을 설정하면 실행할 때 동적 권한을 획득해야 합니다. 아래 방법류는 직접 사용할 수 있습니다.
//XPermissionUtils
public static int PHONE = 0x00;//  
    public static int LOCATION = 0x01;//  
    public static int CAMERA = 0x02;//  
    public static int AUDIO = 0x03;//  
    public static int EXTERNAL = 0x04;//  

    private static int mRequestCode = -1;

    private static OnPermissionListener mOnPermissionListener;

    public interface OnPermissionListener {

        void onPermissionGranted();

        void onPermissionDenied();
    }

    @TargetApi(Build.VERSION_CODES.M)
    public static void requestPermissions(Context context, int requestCode
            , String[] permissions, OnPermissionListener listener) {
        if (context instanceof Activity) {
            mOnPermissionListener = listener;
            List deniedPermissions = getDeniedPermissions(context, permissions);
            if (deniedPermissions.size() > 0) {
                mRequestCode = requestCode;
                ((Activity) context).requestPermissions(deniedPermissions
                        .toArray(new String[deniedPermissions.size()]), requestCode);

            } else {
                if (mOnPermissionListener != null)
                    mOnPermissionListener.onPermissionGranted();
            }
        } else {
            throw new RuntimeException("Context must be an Activity");
        }
    }

    /**
     *               
     */
    private static List getDeniedPermissions(Context context, String... permissions) {
        List deniedPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
                deniedPermissions.add(permission);
            }
        }
        return deniedPermissions;
    }

    /**
     *       ,  Activity onRequestPermissionsResult()  。
     */
    public static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (mRequestCode != -1 && requestCode == mRequestCode) {
            if (mOnPermissionListener != null) {
                if (verifyPermissions(grantResults)) {
                    mOnPermissionListener.onPermissionGranted();
                } else {
                    mOnPermissionListener.onPermissionDenied();
                }
            }
        }
    }

    /**
     *              
     */
    private static boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

간단하고 난폭한 사용으로 액티브에서 권한이 필요한 곳에서 직접 사용하면 된다
 XPermissionUtils.requestPermissions(this, 1, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, new XPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                   //      ,        
                }

                @Override
                public void onPermissionDenied() {
                 //      ,        
                }
            });

//  ,   activity       
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        XPermissionUtils.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

다음은 위치 획득 방법 종류입니다
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class LocationUtils{
private staticStringTAG="LocationUtil";
public static voidrequestLocation(finalContext context) {
XPermissionUtils.requestPermissions(context,RequestCode.LOCATION, newString[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,}
, newXPermissionUtils.OnPermissionListener() {
@Override
public voidonPermissionGranted() {
startLocation(context);
}
@Override
public voidonPermissionDenied() {
DialogUtil.showAlertDialog(context,"  ");
}
});
}
private static voidstartLocation(Context context) {
//         
LocationManager locationManager = (LocationManager) context.getSystemService(Context
.LOCATION_SERVICE);
//            
List providers = locationManager.getProviders(true);
if(providers ==null)return;
//  Location
if(ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED&& ActivityCompat.checkSelfPermission(context,Manifest
.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//  public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
List providerSortList =new ArrayList<>();//        ,gps、net、passive
if(providers.contains(LocationManager.GPS_PROVIDER)) {
Log.d(TAG,"GPS_PROVIDER");
providerSortList.add(LocationManager.GPS_PROVIDER);
}
if(providers.contains(LocationManager.NETWORK_PROVIDER)) {
Log.d(TAG,"NETWORK_PROVIDER");
providerSortList.add(LocationManager.NETWORK_PROVIDER);
}
if(providers.contains(LocationManager.PASSIVE_PROVIDER)) {
Log.d(TAG,"PASSIVE_PROVIDER");
providerSortList.add(LocationManager.PASSIVE_PROVIDER);
}
String locationProvider ="";
for(inti =0;i < providerSortList.size();i++) {
String provider = providerSortList.get(i);
Log.d(TAG,"    :"+ provider);
Location location = locationManager.getLastKnownLocation(provider);
if(location !=null) {
locationProvider = provider;
Log.d(TAG,"    :"+ provider);
saveLocation(location);
break;
}else{
Log.d(TAG,"    :"+ provider);
}
}
if(!TextUtils.isEmpty(locationProvider)) {
locationManager.requestLocationUpdates(locationProvider,3000,1,locationListener);
}
}
staticLocationListenerlocationListener=newLocationListener() {
@Override
public voidonStatusChanged(String provider, intstatus,Bundle arg2) {
}
@Override
public voidonProviderEnabled(String provider) {
}
@Override
public voidonProviderDisabled(String provider) {
}
@Override
public voidonLocationChanged(Location location) {
//        ,    
saveLocation(location);
}
};
/**
*              
*/
private static voidsaveLocation(Location location) {
if(location !=null) {
doublelatitude = location.getLatitude();
doublelongitude = location.getLongitude();
Log.d(TAG,"latitude:"+ latitude);
Log.d(TAG,"longitude:"+ longitude);
}
}
}

여기

좋은 웹페이지 즐겨찾기