2011-08-26 40 views
78

Tôi thiết kế một chức năng có thể lấy/đặt tài nguyên từ SD và nếu không tìm thấy từ sd rồi lấy từ Asset và nếu có thể ghi nội dung trở lại SD
Chức năng này có thể kiểm tra bằng lời gọi phương thức nếu SD được gắn và có thể truy cập ...Làm cách nào để có thể kiểm tra thời gian chạy mà không cần thoát SecurityException?

boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); 

chức năng của tôi được thiết kế có thể được sử dụng từ một ứng dụng (dự án) khác (có hoặc không có android.permission.WRITE_EXTERNAL_STORAGE)

Sau đó, tôi muốn kiểm tra xem ứng dụng hiện có này quyền cụ thể mà không cần chơi với SecurityException.

Có tồn tại cách "đẹp" để tham khảo các quyền hiện tại được xác định khi chạy không?

Trả lời

160

Bạn có thể sử dụng chức năng Context.checkCallingorSelfPermission() cho việc này. Dưới đây là một ví dụ:

private boolean checkWriteExternalPermission() 
{ 
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 
    int res = getContext().checkCallingOrSelfPermission(permission); 
    return (res == PackageManager.PERMISSION_GRANTED);    
} 
+0

Phương pháp này có thể đưa ra một nguy cơ bảo mật. – TalMihr

+13

@TalMihr tại sao bạn tin rằng 'checkCallingOrSelfPermission() 'đặt ra một nguy cơ bảo mật? – William

+0

@inazaruk, có thể cấp quyền nếu không được hệ thống cấp không? –

46

Đây là một giải pháp khác cũng

PackageManager pm = context.getPackageManager(); 
int hasPerm = pm.checkPermission(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    context.getPackageName()); 
if (hasPerm != PackageManager.PERMISSION_GRANTED) { 
    // do stuff 
} 
+0

Vì vậy, tôi nên chỉ quấn mã bên trong đó nếu tuyên bố? Tôi đã thực hiện việc này để xem liệu người dùng có nhận được cuộc gọi hay đang gọi điện thoại, để tắt âm thanh: http://snag.gy/uIxsv.jpg –

+0

Làm điều đó khiến tôi gặp nhiều lỗi ... http: //snag.gy/cF7JU.jpg –

+0

Sự khác biệt khi gọi gói cho phép hoặc iPC là gì? – htafoya

17

Bạn cũng có thể sử dụng này:

private boolean doesUserHavePermission() 
{ 
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); 
    return result == PackageManager.PERMISSION_GRANTED; 
} 
11

Giống như Google documentation:

// Assume thisActivity is the current activity 
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE); 
7

Sharing phương pháp của tôi trong trường hợp ai cần chúng:

/** Determines if the context calling has the required permission 
* @param context - the IPC context 
* @param permissions - The permissions to check 
* @return true if the IPC has the granted permission 
*/ 
public static boolean hasPermission(Context context, String permission) { 

    int res = context.checkCallingOrSelfPermission(permission); 

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED")); 

    return res == PackageManager.PERMISSION_GRANTED; 

} 

/** Determines if the context calling has the required permissions 
* @param context - the IPC context 
* @param permissions - The permissions to check 
* @return true if the IPC has the granted permission 
*/ 
public static boolean hasPermissions(Context context, String... permissions) { 

    boolean hasAllPermissions = true; 

    for(String permission : permissions) { 
     //you can return false instead of assigning, but by assigning you can log all permission values 
     if (! hasPermission(context, permission)) {hasAllPermissions = false; } 
    } 

    return hasAllPermissions; 

} 

Và để gọi nó là:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] { 
       android.Manifest.permission.ACCESS_WIFI_STATE, 
       android.Manifest.permission.READ_PHONE_STATE, 
       android.Manifest.permission.ACCESS_NETWORK_STATE, 
       android.Manifest.permission.INTERNET, 
     }); 
1

Mã mà hoạt động tốt đối với tôi là: -

final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 102; 
    if ((ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { 

       requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
         MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); 
      } else { 
     // user already provided permission 
       // perform function for what you want to achieve 
    } 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 

    boolean canUseExternalStorage = false; 

    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: { 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       canUseExternalStorage = true; 
      } 

      if (!canUseExternalStorage) { 
       Toast.makeText(getActivity(), "Cannot use this feature without requested permission", Toast.LENGTH_SHORT).show(); 
      } else { 
       // user now provided permission 
       // perform function for what you want to achieve 
      } 
     } 
     } 
} 
5

Bạn nên kiểm tra xem có quyền theo cách sau (như được mô tả ở đây Android permissions):

int result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE); 

sau đó, so sánh kết quả của bạn cho một trong hai:

result == PackageManager.PERMISSION_DENIED 

hay:

result == PackageManager.PERMISSION_GRANTED 
+0

Cảm ơn. Điều này rất hữu ích. –

0

Bật GPS vị trí Android Studio

  1. Thêm entry phép trong AndroidManifest.xml

  1. MapsActivity.java

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 
    
    private GoogleMap mMap; 
    private Context context; 
    private static final int PERMISSION_REQUEST_CODE = 1; 
    Activity activity; 
    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 
    
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        context = getApplicationContext(); 
        activity = this; 
        super.onCreate(savedInstanceState); 
        requestPermission(); 
        checkPermission(); 
        setContentView(R.layout.activity_maps); 
        // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
          .findFragmentById(R.id.map); 
        mapFragment.getMapAsync(this); 
    
    } 
    
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
        mMap = googleMap; 
        LatLng location = new LatLng(0, 0); 
        mMap.addMarker(new MarkerOptions().position(location).title("Marker in Bangalore")); 
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); 
        mMap.setMyLocationEnabled(true); 
    } 
    
    private void requestPermission() { 
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) { 
         Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show(); 
        } else { 
         ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE); 
        } 
    } 
    
    private boolean checkPermission() { 
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION); 
        if (result == PackageManager.PERMISSION_GRANTED) { 
         return true; 
        } else { 
         return false; 
        } 
    } 
    
Các vấn đề liên quan