首先配置一个布局:
然后在activity中把发短信的代码写出来:
package com.ydl.smssender;import java.util.ArrayList;//省略导包public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View v){ //拿到用户输入的号码和内容 EditText et_phone = (EditText) findViewById(R.id.et_phone); EditText et_content = (EditText) findViewById(R.id.et_content); String phone = et_phone.getText().toString(); String content = et_content.getText().toString(); //1.获取短信管理器 SmsManager sm = SmsManager.getDefault(); //2.切割短信,把长短信分成若干个小短信 ArrayList发短信是需要系统权限的:smss = sm.divideMessage(content);//an ArrayList of strings that, in order, comprise the original message //3.for循环把集合中所有短信全部发出去 for (String string : smss) { sm.sendTextMessage(phone, null, string, null, null);//Send a text based SMS. } } }
效果:
开了两个模拟器,实现了发短信功能。