android短信管理器-SmsManager

利用短信管理器SmsManager编写简易短信发送器

SMSActivity类代码:
package com.example.androidtest;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class SMSActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sms);
		Button btnSend = (Button)findViewById(R.id.btn_send);
		
		//为发送短信按钮添加事件
		btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TextView telNumber = (TextView)findViewById(R.id.telnumber); 
				TextView telContent = (TextView)findViewById(R.id.content);
				String sTelNumber = telNumber.getText().toString();
				String sContent = telContent.getText().toString();
				//检查手机号码是否为空
				if("".equals(sTelNumber.trim())){
					Toast.makeText(SMSActivity.this, "请输入手机号码", 1).show();
					return;
				}
				SmsManager smsManager = SmsManager.getDefault();
				List<String> contents =  smsManager.divideMessage(sContent); //当短信内容过多时,对短信进行拆分
				//循环发送短信
				for(String _content : contents){
					smsManager.sendTextMessage(sTelNumber, null, _content, null, null);
				}
				
				Toast.makeText(SMSActivity.this, "已发送", 1).show();
				//清空手机号码和短信内容
				telNumber.setText("");
				telContent.setText("");
			}
		});
	}

}

需要注意的是,在这里我们用到了发短息服务,因此我们必须申请发短息的权限:在AndroidMainfest.xml中添加 <uses-permission android:name="android.permission.SEND_SMS"/>

这里,我们用到了SmsManager类中的几个重要的方法:
divideMessage(String text):当短信内容超过每条短信的字数限制时,我们对短信内容拆分成多条发送
sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent);

destinationAddress送短信的地址(也就是号码)
scAddress短信服务中心,如果为null,就是用当前默认的短信服务中心
text短信内容
sentIntent如果不为null,当短信发送成功或者失败时,这个PendingIntent会被广播出去成功的结果代码是Activity.RESULT_OK,或者下面这些错误之一  :RESULT_ERROR_GENERIC_FAILURERESULT_ERROR_RADIO_OFFRESULT_ERROR_NULL_PDU
对于 RESULT_ERROR_GENERIC_FAILURE这个sentIntent可能包括额外的"errorCode",包含一些具体有用的信息帮助检查 。基于SMS控制的全部程序检查 sentIntent. 如果 sentIntent 为空,the caller will be checked against all unknown applications, which cause smaller number of SMS to be sent in checking period.
deliveryIntent如果不为null,当这个短信发送到接收者那里,这个PendtingIntent会被广播,状态报告生成的pdu(指对等层次之间传递的数据单位)会拓展到数据("pdu"
测试结果:
发送:



接收:


这里有个问题暂时还没解决,当发送中文信息的时候,接收到的是乱码!不过,貌似真实手机是不会有中文乱码的!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值