发短信

来源:互联网 发布:入门单反推荐2017知乎 编辑:程序博客网 时间:2024/04/25 12:55

在res——>layout——>activity_main.xml

<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"    tools:context=".MainActivity"    android:orientation="vertical" >   <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="请输入手机号"         android:textSize="20sp"        android:layout_marginTop="10dp"/><EditText     android:id="@+id/et_phone"    android:layout_width="match_parent"    android:layout_height="wrap_content"    /><TextView       android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="请输入短信内容"             android:textSize="20sp"            android:layout_marginTop="10dp"/><EditText     android:id="@+id/et_content"    android:layout_width="match_parent"    android:layout_height="wrap_content"    /><Button     android:id="@+id/send"    android:layout_width="wrap_content"    android:layout_height="wrap_content"     android:text="发送"/></LinearLayout></span>

在MainActivity.java下

public class MainActivity extends Activity {        private Button send;private EditText content;private EditText phone;@Override        protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findView();//调用下面的方法
//设置一个按钮监听        send.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {//获取EditText中的内容String _phone=phone.getText().toString();String _content=content.getText().toString();
//判断EditText是否为空,如果为空,则吐司;不为空,继续往下走if(TextUtils.isEmpty(_phone)||TextUtils.isEmpty(_content)){Toast.makeText(MainActivity.this,"手机号或者是短信内容不能为空",1).show();}else{</span>
//获取发短信的对象SmsManager sms=SmsManager.getDefault();</span>
//判断内容的长度是否大于70if(_content.length()>70){</span>
//内容的长度大于70的话,将内容进行分成几部分放入list集合中List<String> content_=sms.divideMessage(_content);</span>
//遍历list集合中的内容for(String content1:content_){</span>
//_phone:要发送的短信的号码,content1:要发送短信的内容sms.sendTextMessage(_phone,null, content1, null, null);}}else{sms.sendTextMessage(_phone,null,_content, null, null);}<span style="white-space:pre"></span>Toast.makeText(MainActivity.this, "发送成功", 1).show();}}        });    } @Override    public boolean onCreateOptionsMenu(Menu menu) {       getMenuInflater().inflate(R.menu.main, menu);         return true;    
 //获取各个组件的引用        public void findView(){        phone = (EditText) findViewById(R.id.et_phone);        content = (EditText) findViewById(R.id.et_content);        send = (Button) findViewById(R.id.send);  }    }

在清单文件AndroidManifest.xml下

//在清单文件下设置发送短信的权限
<uses-permission android:name="android.permission.SEND_SMS"/>





0 0
原创粉丝点击