先說明一下我的功能

是許多TextView的頁面,其中一些TextView內容為電話號碼

按下這個TextView ,需要自動撥號

 

前面的宣告、findViewById、setOnClickListener 的部分就不說了。

 

以下貼上onClick事件,和撥打電話的程式

因為考慮到有可能多個TextView需要去撥打電話,所以將驗證權限到startActivity的部分獨立出去。

 

撥打電話有兩種方式

第一種是開啟撥電話的頁面 => Intent.ACTION_DIAL

這種我直接startActivity就可以了不需要走驗證權限那一塊

 

第二種是直接撥號 =>Intent.ACTION_CALL

必須檢查授權

 

若是沒有做檢查授權那一段,會報出以下錯誤

Exception = java.lang.SecurityException: 
Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xx-xxxx-xxxx cmp=com.android.server.telecom/.components.UserCallActivity }
 from ProcessRecord{a3e7dd7 11468:com.test.test.test/u0a149} (pid=11468, uid=10149) with revoked permission android.permission.CALL_PHONE

 

語法如下

@Override
public void onClick(View view) {
    int iViewID = view.getId();

    //電話號碼onClick
    if(iViewID == R.id.tvTel){
               try{
            //開啟撥號介面
                       //Intent phoneIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+ m_tvTel.getText()));

            //直接撥號
                        Intent phoneIntent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ m_tvTel.getText()));

            callPhone( phoneIntent ) ;

        }catch (Exception e){
            LogUtil.log("Exception = " + e);
        }

    }
}

 

//撥打電話
private void callPhone( Intent intent )throws Exception {

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
        startActivity(intent);
    } else {
        requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1);
    }
}

 

 

然後在設定方面AndroidManifest.xml,需要增加以下兩種設定

權限需要增加

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

 

在<activity 裡面 還需要增加以下

android:exported="true"

 

 

 

參考:

https://developer.android.com/training/permissions/requesting

https://stackoverflow.com/questions/33473436/revoked-permission-android-permission-call-phone

 

arrow
arrow
    文章標籤
    androidapp開發 撥打電話
    全站熱搜

    我的暱稱 發表在 痞客邦 留言(0) 人氣()