欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实战教程第四篇之简单实现短信发送器

程序员文章站 2024-03-02 18:01:28
本文实例为大家分享了android发短信功能的实现方法,供大家参考,具体内容如下 首先配置一个布局:

本文实例为大家分享了android发短信功能的实现方法,供大家参考,具体内容如下

首先配置一个布局:

<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"/>
 

效果:

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

Android实战教程第四篇之简单实现短信发送器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。