android studio 在MainActivity中添加几个按钮实现发送短信的功能
时间: 2023-05-29 16:04:47 浏览: 216
首先,在MainActivity布局文件中添加几个按钮,例如:
```
<Button
android:id="@+id/btn_send_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS" />
<Button
android:id="@+id/btn_choose_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Contact" />
<EditText
android:id="@+id/edit_text_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message" />
```
然后,在MainActivity中添加代码实现发送短信的功能:
```
public class MainActivity extends AppCompatActivity {
private static final int PICK_CONTACT_REQUEST = 1;
private EditText mEditTextSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendSms = findViewById(R.id.btn_send_sms);
btnSendSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendSms();
}
});
Button btnChooseContact = findViewById(R.id.btn_choose_contact);
btnChooseContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseContact();
}
});
mEditTextSms = findViewById(R.id.edit_text_sms);
}
private void sendSms() {
String message = mEditTextSms.getText().toString();
if (!TextUtils.isEmpty(message)) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:" + ""));
intent.putExtra("sms_body", message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
private void chooseContact() {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
mEditTextSms.setText(number);
}
if (cursor != null) {
cursor.close();
}
}
}
}
```
其中,sendSms()方法实现发送短信的功能,chooseContact()方法实现选择联系人的功能。在onActivityResult()方法中获取选择的联系人的电话号码,并将其填充到EditText中。
阅读全文