程序员人生 网站导航

Android简易实战教程--第四话《最简单的短信发送器》

栏目:综合技术时间:2016-07-07 08:50:47

首先配置1个布局:

<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical" > <EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:hint="请输入对方号码" /> <EditText android:id="@+id/et_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:lines="5" android:hint="请输入短信内容" android:gravity="top" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送" android:onClick="send" /> </LinearLayout>
然后在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<String> 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. } } }
发短信是需要系统权限的:

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

效果:

开了两个摹拟器,实现了发短信功能。




------分隔线----------------------------
------分隔线----------------------------

最新技术推荐