1. 程式人生 > >Android之許可權檢查(解決未獲取使用者許可權允許)

Android之許可權檢查(解決未獲取使用者許可權允許)

本文主要是記錄一些零碎的東西

最近在專案中發現需要做Android的許可權檢查,要不然會在某些機型上失敗。

但是這些都不足以解決我的問題,我遇見的是在某些機型上失敗,沒有彈出需要獲取許可權的彈窗,個人感覺主要的解決方案就是

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)”介面,讓使用者自己去修改許可權。

本文只是已讀取聯絡人為入口,只是提供一個結局思路,其他許可權可以類似。