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

Android开发获取短信的内容并截取短信

程序员文章站 2023-12-16 15:04:46
1、首先我们要写一个广播接收器,当我们的手机收到短信时,系统会自动发送一个广播,我们只需要接收到这条广播就可以了 2、在广播里面,我们重写的onreceive()方法,通...

1、首先我们要写一个广播接收器,当我们的手机收到短信时,系统会自动发送一个广播,我们只需要接收到这条广播就可以了

2、在广播里面,我们重写的onreceive()方法,通过里面的intent写到的bundle就可以拿到短信的内容,

3、清单文件里面我们必须要添加权限,否则无法接收到。

4、为了防止我们的广播接收不到,我们自己写的广播接收器的权限必须要大,以防万一,我设置了1000。

下面上代码,里面的注释也比较详细..

 <?xml version="." encoding="utf-"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.fanlei.cutnotedemo" >
   //接收短信
   <uses-permission android:name="android.permission.receive_sms"/>
   <application
     android:allowbackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/apptheme" >
     <!-- action:name = 的名称是固定的 -->
     <receiver android:name=".notereceiver">
       <intent-filter android:priority="">
         <action android:name="android.provider.telephony.sms_received"/>
       </intent-filter>
     </receiver>
     <activity
       android:name=".mainactivity"
       android:label="@string/app_name" >
       <intent-filter>
         <action android:name="android.intent.action.main" />
         <category android:name="android.intent.category.launcher" />
       </intent-filter>
     </activity>
   </application>
 </manifest>

写一个类,继承broadcastreceiver

android--获取短信的内容,截取短信
 package com.example.fanlei.cutnotedemo;
 import android.content.broadcastreceiver;
 import android.content.context;
 import android.content.intent;
 import android.os.bundle;
 import android.telephony.smsmessage;
 import android.widget.toast;
 import java.text.simpledateformat;
 import java.util.date;
 /**
 * 广播接收器
 */
 public class notereceiver extends broadcastreceiver {
   private static final string sms_received_action = "android.provider.telephony.sms_received";
   @override
   public void onreceive(context context, intent intent) {
     string action = intent.getaction();
     //判断广播消息
     if (action.equals(sms_received_action)){
       bundle bundle = intent.getextras();
       //如果不为空
       if (bundle != null){
         //将pdus里面的内容转化成object[]数组
         object pdusdata[] = (object[]) bundle.get("pdus");
         //解析短信
         smsmessage[] msg = new smsmessage[pdusdata.length];
         for (int i = ;i < msg.length;i++){
           byte pdus[] = (byte[]) pdusdata[i];
           msg[i] = smsmessage.createfrompdu(pdus);
         }
         stringbuffer content = new stringbuffer();//获取短信内容
         stringbuffer phonenumber = new stringbuffer();//获取地址
         stringbuffer receivedata = new stringbuffer();//获取时间
         //分析短信具体参数
         for (smsmessage temp : msg){
           content.append(temp.getmessagebody());
           phonenumber.append(temp.getoriginatingaddress());
           receivedata.append(new simpledateformat("yyyy-mm-dd hh:mm:ss.sss")
               .format(new date(temp.gettimestampmillis())));
         }
         /**
         * 这里还可以进行好多操作,比如我们根据手机号进行拦截(取消广播继续传播)等等
         */
         toast.maketext(context,phonenumber.tostring()+content+receivedata, toast.length_long).show();//短信内容
       }
     }
   }
 }

ps:android获取短信所有内容

public class getmessageinfo { 
  list<messageinfo> list; 
  context context; 
  messageinfo messageinfo; 
  public getmessageinfo(context context) { 
    list = new arraylist<messageinfo>(); 
    this.context = context; 
  } 
  // --------------------------------收到的短息信息---------------------------------- 
  public list<messageinfo> getsmsinfos() { 
    final string sms_uri_inbox = "content://sms/inbox";// 收信箱 
    try { 
      contentresolver cr = context.getcontentresolver(); 
      string[] projection = new string[] { "_id", "address", "person","body", "date", "type" }; 
      uri uri = uri.parse(sms_uri_inbox); 
      cursor cursor = cr.query(uri, projection, null, null, "date desc"); 
      while (cursor.movetonext()) { 
        messageinfo = new messageinfo(); 
        // -----------------------信息---------------- 
        int namecolumn = cursor.getcolumnindex("person");// 联系人姓名列表序号 
        int phonenumbercolumn = cursor.getcolumnindex("address");// 手机号 
        int smsbodycolumn = cursor.getcolumnindex("body");// 短信内容 
        int datecolumn = cursor.getcolumnindex("date");// 日期 
        int typecolumn = cursor.getcolumnindex("type");// 收发类型 1表示接受 2表示发送 
        string nameid = cursor.getstring(namecolumn); 
        string phonenumber = cursor.getstring(phonenumbercolumn); 
        string smsbody = cursor.getstring(smsbodycolumn); 
        date d = new date(long.parselong(cursor.getstring(datecolumn))); 
        simpledateformat dateformat = new simpledateformat("yyyy-mm-dd " + "\n" + "hh:mm:ss"); 
        string date = dateformat.format(d); 
        // --------------------------匹配联系人名字-------------------------- 
        uri personuri = uri.withappendedpath(contactscontract.phonelookup.content_filter_uri,phonenumber); 
        cursor localcursor = cr.query(personuri, new string[] {phonelookup.display_name, phonelookup.photo_id,phonelookup._id }, null, null, null); 
        system.out.println(localcursor.getcount()); 
        system.out.println("之前----"+localcursor); 
        if (localcursor.getcount()!=0) { 
          localcursor.movetofirst(); 
          system.out.println("之后----"+localcursor); 
          string name = localcursor.getstring(localcursor.getcolumnindex(phonelookup.display_name)); 
          long photoid = localcursor.getlong(localcursor.getcolumnindex(phonelookup.photo_id)); 
          long contactid = localcursor.getlong(localcursor.getcolumnindex(phonelookup._id)); 
          messageinfo.setname(name); 
          // 如果photoid 大于0 表示联系人有头像 ,如果没有给此人设置头像则给他一个默认的 
          if (photoid > 0) { 
           uri uri1 = contenturis.withappendedid(contactscontract.contacts.content_uri,contactid); 
            inputstream input = contactscontract.contacts.opencontactphotoinputstream(cr, uri1); 
            messageinfo.setcontactphoto(bitmapfactory.decodestream(input)); 
          } else { 
            messageinfo.setcontactphoto(bitmapfactory.decoderesource(context.getresources(),r.drawable.ic_launcher)); 
          } 
        }else{ 
            messageinfo.setname(phonenumber); 
            messageinfo.setcontactphoto(bitmapfactory.decoderesource(context.getresources(), r.drawable.ic_launcher)); 
          } 
        localcursor.close(); 
        messageinfo.setsmscontent(smsbody); 
        messageinfo.setsmsdate(date); 
        list.add(messageinfo); 
      } 
    } catch (sqliteexception e) { 
      e.printstacktrace(); 
    } 
    return list; 
  } 
} 

以上内容是小编给大家分享的android开发获取短信的内容并截取短信,希望大家喜欢。

上一篇:

下一篇: