Android 调用系统发送短信界面,预设号码和短信内容

来源:互联网 发布:陀螺效应 知乎 编辑:程序博客网 时间:2024/05/17 04:01

相信很多开发的同学们免不了遇到过这个问题,就是调用系统的发送短信界面,其实这个问题还是比较容易的,只需向系统发送一个Intent,并附带相关参数就可以了,下面以一个demo说明。

类似下图的界面


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <Button        android:id="@+id/btn_send"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_marginRight="@dimen/padding_small"        android:gravity="center"        android:paddingLeft="@dimen/padding_small"        android:paddingRight="@dimen/padding_small"        android:text="@string/btn_send" />    <EditText        android:id="@+id/edit_phone_number"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_alignBottom="@id/btn_send"        android:layout_marginLeft="@dimen/padding_small"        android:layout_marginRight="@dimen/padding_small"        android:layout_toLeftOf="@id/btn_send"        android:hint="@string/edittext_hint"        android:inputType="phone"        android:paddingLeft="@dimen/padding_small" /></RelativeLayout>

然后在MainActivity中编写相应的Java代码就可以了,我们操作很简单,在EditText中输入号码,然后点击Send,就跳到系统发送短信界面,并且接收人一栏里填入号码。相关的代码如下:

获取控件,响应Button的点击事件:

@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mEditText = (EditText) findViewById(R.id.edit_phone_number);mButton = (Button) findViewById(R.id.btn_send);mButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String phoneNumber = mEditText.getText().toString();if (!TextUtils.isEmpty(phoneNumber)) {sendSmsWithNumber(MainActivity.this, phoneNumber);}}});}

向指定号码发送短信:

/** * 调用系统界面,给指定的号码发送短信 *  * @param context * @param number */public void sendSmsWithNumber(Context context, String number) {Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + number));context.startActivity(sendIntent);}
这样点击Send后,就会跳转到系统短信界面了,并且接收人一栏里就是刚才你填写的号码。


同理,要想调用系统发送短信界面后附加短信内容和以上是类似的,只需在Intent中附带相关的参数就可以了。

/** * 调用系统界面,给指定的号码发送短信,并附带短信内容 *  * @param context * @param number * @param body */public void sendSmsWithBody(Context context, String number, String body) {Intent sendIntent = new Intent(Intent.ACTION_SENDTO);sendIntent.setData(Uri.parse("smsto:" + number));sendIntent.putExtra("sms_body", body);context.startActivity(sendIntent);}
截图就不发了,感兴趣的同学自己试验一下就可以了。


第一次使用CSDN的Blog,难道不能上传源码吗?


原创粉丝点击