0%

Android发送短信 SmsManager的使用 返回发送结果 发送超长短信

2011年7月18日加注:如果短信内容过长,可以使用SmsManager.divideMessage(String text)方法自动拆分成一个ArrayList数组,再根据数组长度循环发送,或者直接用sendMultipartTextMessage方法发送,参数与sendTextMessage类似,无非是短信内容变成了用divideMessage拆成的ArrayList,两个广播也是,所以不再写例子. 前面说到可以通过发送Intent的方式跳转到短信发送界面,让用户自行发送短信,今天学习的SmsManager可以在后台发送短信,无需用户操作,某些无良开发者就用这个SmsManager功能在后台偷偷给SP发短信,导致用户话费被扣.其实,这些应用还是很好分辨的,因为要通过SmsManager发送短信,必须添加android.permission.SEND_SMS权限,在安装的时候稍稍注意就可以了,当然也有通过在程序中下载其他有短信权限的应用,后台安装发送短信的情况,在安装的时候注意该应用是否有安装其他应用的权限(android.permission.INSTALL_PACKAGES),如果没有这个权限,安装应用是必须先经过用户点击的. 下面贴上代码:

package com.hello;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;

public class HelloWorldActivity extends Activity {
    /** Called when the activity is first created. */
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String action="com.pocketdigi";
        
        sendReceiver receiver=new sendReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(action);
        registerReceiver(receiver,filter);
        //必须先注册广播接收器,否则接收不到发送结果
        
        SmsManager smsMgr = SmsManager.getDefault(); 
        Intent intent = new Intent(action);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
        smsMgr.sendTextMessage("10086", null, "1561", pi, null);
        //参数分别为号码,短信服务中心号码(null即可),短信内容,短信发送结果广播PendingIntent,短信到达广播
     //关于短信到达广播(对方接收到短信时广播),据网上说,中国移动有,中国联通没有,有兴趣的同学自己试试,没兴趣直接null
    }
    
    class sendReceiver extends BroadcastReceiver{
        //写个接收器
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            int resultCode = getResultCode();
            if(resultCode==Activity.RESULT_OK){
                System.out.println("发送成功");
            }else{
                System.out.println("发送失败");
            }
        }
    }
}