android拨打电话实验分析,在安卓中编程拨打电话案例源码
时间: 2024-05-13 10:19:51 浏览: 121
以下是一个简单的 Android 拨打电话的实验:
首先,在 AndroidManifest.xml 中添加以下权限:
```xml
<uses-permission android:name="android.permission.CALL_PHONE" />
```
然后,在你的 Activity 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CALL_PHONE = 1;
private EditText mPhoneNumberEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPhoneNumberEditText = findViewById(R.id.phone_number_edit_text);
Button callButton = findViewById(R.id.call_button);
callButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumber = mPhoneNumberEditText.getText().toString();
if (phoneNumber.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
} else {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL_PHONE);
} else {
callPhoneNumber(phoneNumber);
}
}
}
});
}
private void callPhoneNumber(String phoneNumber) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CALL_PHONE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String phoneNumber = mPhoneNumberEditText.getText().toString();
callPhoneNumber(phoneNumber);
} else {
Toast.makeText(MainActivity.this, "Permission denied to make phone calls", Toast.LENGTH_SHORT).show();
}
}
}
}
```
在这段代码中,我们首先获取了用户输入的电话号码,然后检查应用是否被授予 CALL_PHONE 权限。如果没有被授予,我们就请求该权限。如果已经被授予,我们就调用 callPhoneNumber 方法来拨打电话。当用户授予或拒绝权限时,我们在 onRequestPermissionsResult 方法中处理相应的操作。
需要注意的是,调用 ACTION_CALL 意图将直接拨打电话,而不提示用户确认。如果你想要提示用户确认,可以使用 ACTION_DIAL 意图代替。
阅读全文