新建了CallPhone方法,如下:
1 private void CallPhone() { 2 String number = et_number.getText().toString(); 3 if (TextUtils.isEmpty(number)) { 4 // 提醒用戶 5 Toast.makeText(MainActivity.this, "我叫吐司,請填寫號碼,行不行!!!", Toast.LENGTH_SHORT).show(); 6 } else { 7 // 撥號:激活系統的撥號組件 8 Intent intent = new Intent(); // 意圖對象:動作 + 數據 9 intent.setAction(Intent.ACTION_CALL); // 設置動作 10 Uri data = Uri.parse("tel:" + number); // 設置數據 11 intent.setData(data); 12 startActivity(intent); // 激活Activity組件 13 } 14 }
要記得在清單文件AndroidManifest.xml中添加權限
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="***"> 4 5 <application 6 ...... 7 </application> 8 <uses-permission android:name="android.permission.CALL_PHONE"/> 9 10 </manifest>
為方便理解,給出activyti_main.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <LinearLayout 10 android:layout_width="match_parent" 11 android:layout_height="match_parent" 12 android:orientation="vertical"> 13 14 <EditText 15 android:id="@+id/ed" 16 android:layout_width="match_parent" 17 android:layout_height="wrap_content" 18 android:hint="請輸入手機號" /> 19 20 <Button 21 android:id="@+id/button" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:text="撥打" /> 25 </LinearLayout> 26 27 28 </android.support.constraint.ConstraintLayout>
在onCreate()中找到控件,給南牛添加點擊事件,調用此方法即可。
順便寫一下從網上找到的android6.0動態獲取權限的代碼(親測可用):
1 // 檢查是否獲得了權限(Android6.0運行時權限) 2 //權限沒有獲得 3 if (ContextCompat.checkSelfPermission(MainActivity.this, 4 Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){ 5 // 沒有獲得授權,申請授權 6 if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, 7 Manifest.permission.CALL_PHONE)) { 8 // 返回值: 9 // 如果app之前請求過該權限,被用戶拒絕, 這個方法就會返回true. 10 // 如果用戶之前拒絕權限的時候勾選了對話框中”Don’t ask again”的選項,那么這個方法會返回false. 11 // 如果設備策略禁止應用擁有這條權限, 這個方法也返回false. 12 // 彈窗需要解釋為何需要該權限,再次請求授權 13 Toast.makeText(MainActivity.this, "請授權!", Toast.LENGTH_LONG).show(); 14 15 // 幫跳轉到該應用的設置界面,讓用戶手動授權 16 Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 17 Uri uri = Uri.fromParts("package", getPackageName(), null); 18 intent.setData(uri); 19 startActivity(intent); 20 }else{ 21 // 不需要解釋為何需要該權限,直接請求授權 22 ActivityCompat.requestPermissions(MainActivity.this, 23 new String[]{Manifest.permission.CALL_PHONE}, 24 MY_PERMISSIONS_REQUEST_CALL_PHONE); 25 } 26 }else { 27 // 已經獲得授權,可以打電話 28 CallPhone(); 29 }
