要制作一个默认的拨号应用程序,你需要使用Android的电话拨号功能和权限。以下是一个简单的示例代码:
activity_main.xml:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CALL_PHONE = 1;
private EditText editTextPhoneNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
Button buttonDial = findViewById(R.id.buttonDial);
buttonDial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makePhoneCall();
}
});
}
private void makePhoneCall() {
String phoneNumber = editTextPhoneNumber.getText().toString().trim();
if (phoneNumber.isEmpty()) {
Toast.makeText(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 {
String dial = "tel:" + phoneNumber;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
}
}
}
@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) {
makePhoneCall();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
这个示例代码包含了获取拨号权限、拨号和处理权限请求的功能。当用户点击拨号按钮时,它会检查是否有拨号权限,如果没有则会请求权限。如果有权限,它会创建一个拨号意图并启动拨号操作。