我的android 第二天 - 短信发送器
今天学做一个短信发送器。
界面分析与设计
布局:LinearLayout(线性布局、垂直方向)
控件:2个TextView(文本框)、2个EditVIew(编辑框)、Button(命令按钮)
提示与要求:
电话号码编辑框只能输入数字
对短信编辑框设置多行 android:minLines="“
对EditView、Button添加id,用于获取该对象
优化:对编辑框实现提示,减少控件,android:hint="“
可对Button添加android:onClick=“方法名”,实现按钮单击绑定方法
开始做界面。
<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" android:background="@drawable/bg_pes" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:padding="@dimen/padding_medium" android:text="发短信" android:textSize="30sp" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_toLeftOf="@+id/textView1" android:src="@drawable/ic_apple" /> <EditText android:id="@+id/tel_edt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/imageView1" android:layout_toRightOf="@+id/imageView1" android:layout_marginLeft="20dp" android:ems="10" android:hint="电话号码" android:inputType="phone" /> <EditText android:id="@+id/sms_edt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tel_edt" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:hint="亲,写短信" android:minLines="4" /> <Button android:id="@+id/send_bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/sms_edt" android:text="发送" android:onClick="sendSms" /> </RelativeLayout>
然后对activity引用布局:setContentView(R.layout.activity_sms)
引用编辑框,获取电话号码及短信findViewById(R.id.number)
setContentView(R.layout.activity_sms); telEdt=(EditText) findViewById(R.id.tel_edt); smsEdt=(EditText) findViewById(R.id.sms_edt);
引用Button按钮,对拨号按钮添加监听(可在布局文件中添加)
SmsManager 短信管理器、分拆短信(短信大于70字符)
Toast:吐司,信息提示
//用户输入的电话号码 String tel=telEdt.getText().toString().trim(); //用户输入的短信内容 String sms=smsEdt.getText().toString().trim(); //获取短信管理器 SmsManager mgr=SmsManager.getDefault(); //puds :140个字符 ArrayList<String> data =mgr.divideMessage(sms); for(String p:data){ //发送短信 : mgr.sendTextMessage(tel, null, p, null, null); } //吐司,在系统瞬时显示, Toast.makeText(this, "亲,该回信息了", Toast.LENGTH_LONG).show(); //输出日志 Log.d(TAG, tel+sms);
添加发短信权限<uses-permissionandroid:name="android.permission.SEND_SMS"/>
注册Activity <activityandroid:name=".SmsActivity">