要在Android应用程序中发送短信,需要在AndroidManifest.xml文件中声明发送短信的权限。以下是一个包含发送短信权限声明的示例:
打开项目的AndroidManifest.xml文件。
在
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
private EditText phoneNumberEditText;
private EditText messageEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEditText = findViewById(R.id.phone_number_edit_text);
messageEditText = findViewById(R.id.message_edit_text);
Button sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phoneNumber = phoneNumberEditText.getText().toString();
String message = messageEditText.getText().toString();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_GRANTED) {
sendSMS(phoneNumber, message);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS},
PERMISSION_REQUEST_CODE);
}
}
});
}
private void sendSMS(String phoneNumber, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "短信发送成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "短信发送失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String phoneNumber = phoneNumberEditText.getText().toString();
String message = messageEditText.getText().toString();
sendSMS(phoneNumber, message);
} else {
Toast.makeText(this, "发送短信权限被拒绝", Toast.LENGTH_SHORT).show();
}
}
}
}
这个示例代码中包含一个按钮和两个文本框,用户可以输入电话号码和短信内容。当点击发送按钮时,应用程序将检查是否已获得发送短信的权限。如果已经获得权限,则调用sendSMS函数发送短信。如果没有获得权限,则请求发送短信的权限。在onRequestPermissionsResult方法中处理权限请求的结果。