安卓端发送短信

来源:互联网 发布:研华数据采集卡 编辑:程序博客网 时间:2024/05/20 11:23

编辑如图所示界面
这里写图片描述
代码如下所示、

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"    android:orientation="vertical"   >    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入电话号码"        android:id="@+id/et1"/>    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入短信内容"        android:id="@+id/et2"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="发送"        android:id="@+id/btn"/></LinearLayout>

接下来写类

package mooc.java.sendmsm;import android.support.v7.app.AppCompatActivity;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 java.util.ArrayList;public class MainActivity extends AppCompatActivity {    private EditText et1;    private EditText et2;    private Button btn;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et1 = (EditText) findViewById(R.id.et1);        et2 = (EditText) findViewById(R.id.et2);        btn = (Button) findViewById(R.id.btn);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                String number = et1.getText().toString();                String content = et2.getText().toString();                SmsManager manager = SmsManager.getDefault();                ArrayList<String> texts=manager.divideMessage(content);                for(String text:texts) {                    manager.sendTextMessage(number,null,text,null,null);                }                Toast.makeText(MainActivity.this,"发送成功",Toast.LENGTH_LONG).show();            }        });    }}

最重要是要写权限

<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

所涉及的主要知识

1)SmsManager manager = SmsManager.getDefault();//获得默认的短信管理器2)ArrayList<String> texts=manager.divideMessage(content);根据常识,短信太长的话,会被分开发送,所以这句是把短信分开,并赋值给集合中3)manager.sendTextMessage(number,null,text,null,null);第一个参数为:发送的手机号第二个参数为:短信服务中心,如果为null,就是用当前默认的短信服务中心第三个参数为:短信内容第四个参数为: 如果不为null,当短信发送成功或者失败时,这个                   PendingIntent会被广播出去成功的结果代码是Activity.RESULT_OK第四个参数为:如果不为null,当这个短信发送到接收者那里,这个PendtingIntent会被广播,状态报告生成的pdu(指对等层次之间传递的数据单位)会拓展到数据("pdu"
0 0
原创粉丝点击