在Android中发送短信和彩信,监听短信并显示

发送短信:

String body="this is sms demo";
Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
startActivity(mmsintent);

 

 

发送彩信:

StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);

 

 

广播监听短信并显示内容:

AndroidManifest.xml中添加
<receiver android:name=".receive">            
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>


再写一个广播监听
public class receive extends BroadcastReceiver
{
    String receiveMsg = "";
    public void onReceive(Context context, Intent intent)
    {
        SmsMessage[] msg= null;
        
     if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
     {
          //StringBuilder buf = new StringBuilder();
          Bundle bundle = intent.getExtras();
          if (bundle != null) {
                  Object[] pdusObj = (Object[]) bundle.get("pdus");
                  msg= new SmsMessage[pdusObj.length];
                  for (int i = 0; i<pdusObj.length; i++)
                          msg[i] = SmsMessage.createFromPdu ((byte[]) pdusObj[i]);
          }
   
     
     for(int i = 0; i < msg.length; i++)
     {
         String msgTxt = msg[i].getMessageBody();
         if (msgTxt.equals("Testing!"))
         {
             Toast.makeText(context, "success!", Toast.LENGTH_LONG).show();
             return;
         }
         else
         {
             Toast.makeText(context, msgTxt, Toast.LENGTH_LONG).show();
             return;
         }
     }
       return;
}


}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值