Android之权限检查(解决未获取用户权限允许)

本文主要是记录一些零碎的东西

最近在项目中发现需要做Android的权限检查,要不然会在某些机型上失败。

API23以上的版本有提供好权限申请,具体参考API:https://developer.android.com/guide/topics/security/permissions.html

或者http://www.jianshu.com/p/57798618bd90#rd

但是这些都不足以解决我的问题,我遇见的是在某些机型上失败,没有弹出需要获取权限的弹窗,个人感觉主要的解决方案就是

try-catch 或者 if 判断一下,以读取通讯录联系人为例

布局文件先添加权限

<!-- 读取通讯录 -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
布局文件我就使用了一个button测试一下

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="permissionCheck"
        android:text="@string/hello_world" />
然后在activity里,贴上全部代码

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 读取联系人
	 * @param view
	 */
	public void permissionCheck(View view){
		
		startActivityForResult(new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_URI), 520);
		
	}
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	if (data == null) { 
            return; 
        } 
    	if(requestCode == 520 & resultCode  == Activity.RESULT_OK){
        	// 读取联系人
//    		Log.i("slack", data.getData().toString());
            Uri uri = data.getData(); 
            if (uri == null) { 
                return ; 
            } 
            Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
            Log.i("slack", cursor.moveToFirst()+" " + cursor.getColumnCount()+" "+cursor.getCount());
            if (cursor.moveToFirst()) { 
//              if (cursor.moveToNext()) { 
              	String phoneName = cursor.getString(cursor 
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
              	
              	Log.i("slack", "phoneName:"+phoneName);
              	String hasPhone = cursor.getString(cursor 
                                  .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
//                  Log.i("slack", hasPhone);
              	String id = cursor.getString(cursor 
                          .getColumnIndex(ContactsContract.Contacts._ID)); 
                  if (hasPhone.equalsIgnoreCase("1")) { 
                      hasPhone = "true"; 
                  } else { 
                      hasPhone = "false"; 
                  } 
                  if (Boolean.parseBoolean(hasPhone)) { 
                  	Cursor phones = getContentResolver().query( 
                              ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                              null, 
                              ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
                                      + " = " + id, null, null); 
                     // 如果有多个电话,默认使用第一个,如果想使用最后一个,使用while,如果想选中间的 ,这里就需要弹出来让用户选择了,待定。。。。。。。。。。
                     while (phones.moveToNext()) { 
                  	   String phoneNumber = phones 
                                  .getString(phones 
                                          .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
                          Log.i("slack", "phoneNumber:"+phoneNumber);
                          
                      } 
                      phones.close(); 
                  } 
              }else{
            	  
            	  // 没有权限,跳到设置界面,调用Android系统“应用程序信息(Application Info)”界面
            	  new AlertDialog.Builder(MainActivity.this)
                  .setMessage("app需要开启读取联系人权限")
                  .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialogInterface, int i) {
                          Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                          intent.setData(Uri.parse("package:" + getPackageName()));
                          startActivity(intent);
                      }
                  })
                  .setNegativeButton("取消", null)
                  .create()
                  .show();
            	  
              } 
//            Log.i("slack", "cursor.close...");
            cursor.close();

    	}
    }
}
其中调用系统的联系人
startActivityForResult(new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_URI), 520);
在activityForResult里,如果没有权限,游标cursor.moveToFirst()会返回false,我在低版本的手机上会弹出权限提示框,在魅族小米上都失败了,加上判断后,其中
android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
调用Android系统“应用程序信息(Application Info)”界面,让用户自己去修改权限。

本文只是已读取联系人为入口,只是提供一个结局思路,其他权限可以类似。





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值