1. 程式人生 > >Android 獲取聯絡人時提示錯誤

Android 獲取聯絡人時提示錯誤

錯誤資訊:java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{765d76f 31960:com.re.mywebview/u0a265} (pid=31960, uid=10265) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS

程式目的:在JS中呼叫Android的介面方法,簡單讀取聯絡人資訊並顯示在html頁面中。

AndroidManifest.xml檔案已經加入了許可權:

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>

修改幾處:

1、targetSdkVersion 27,經查詢資料發現,23以上的版本讀取聯絡人均會出現以上錯誤,修改為22或者22以下。

2、傳遞給js呼叫的業務類中的方法提取到一個執行緒中使用,如:

public class SharpJS {
    @JavascriptInterface
public void contactlist() {
        handler.post(new Runnable() { //add 
            @Override
public void run() {
//method add
                try {
                    System.out.println("contactlist()方法執行了!");
                    String json = buildJson(getContacts());
                    wView
.loadUrl("javascript:show('" + json + "')"); } catch (Exception e) { Log.e("error:",e.getMessage()); }
//method end
            }
        });
    }
    @JavascriptInterface
public void call(final String phone) {
        handler.post(new Runnable() {
            @Override
public void run() {
                System.out.println("call()方法執行了!");
                Intent it = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                try {
                    startActivity(it);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
如果不在同一執行緒中呼叫方法,會報如下錯誤:

 WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {10ec681} called on Looper (JavaBridge, tid 10834) {4483fc6}, FYI main Looper is Looper (main, tid 1) {10ec681}

以上也是查詢資料並實際操作所得,僅供參考。