Android开发获取短信的内容并截取短信
1、首先我们要写一个广播接收器,当我们的手机收到短信时,系统会自动发送一个广播,我们只需要接收到这条广播就可以了
2、在广播里面,我们重写的onReceive()方法,通过里面的Intent写到的Bundle就可以拿到短信的内容,
3、清单文件里面我们必须要添加权限,否则无法接收到。
4、为了防止我们的广播接收不到,我们自己写的广播接收器的权限必须要大,以防万一,我设置了1000。
下面上代码,里面的注释也比较详细..
<?xmlversion="."encoding="utf-"?> <manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fanlei.cutnotedemo"> //接收短信 <uses-permissionandroid: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=的名称是固定的--> <receiverandroid:name=".NoteReceiver"> <intent-filterandroid:priority=""> <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
写一个类,继承BroadcastReceiver
Android--获取短信的内容,截取短信
packagecom.example.fanlei.cutnotedemo;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.telephony.SmsMessage;
importandroid.widget.Toast;
importjava.text.SimpleDateFormat;
importjava.util.Date;
/**
*广播接收器
*/
publicclassNoteReceiverextendsBroadcastReceiver{
privatestaticfinalStringSMS_RECEIVED_ACTION="android.provider.Telephony.SMS_RECEIVED";
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
//判断广播消息
if(action.equals(SMS_RECEIVED_ACTION)){
Bundlebundle=intent.getExtras();
//如果不为空
if(bundle!=null){
//将pdus里面的内容转化成Object[]数组
ObjectpdusData[]=(Object[])bundle.get("pdus");
//解析短信
SmsMessage[]msg=newSmsMessage[pdusData.length];
for(inti=;i<msg.length;i++){
bytepdus[]=(byte[])pdusData[i];
msg[i]=SmsMessage.createFromPdu(pdus);
}
StringBuffercontent=newStringBuffer();//获取短信内容
StringBufferphoneNumber=newStringBuffer();//获取地址
StringBufferreceiveData=newStringBuffer();//获取时间
//分析短信具体参数
for(SmsMessagetemp:msg){
content.append(temp.getMessageBody());
phoneNumber.append(temp.getOriginatingAddress());
receiveData.append(newSimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS")
.format(newDate(temp.getTimestampMillis())));
}
/**
*这里还可以进行好多操作,比如我们根据手机号进行拦截(取消广播继续传播)等等
*/
Toast.makeText(context,phoneNumber.toString()+content+receiveData,Toast.LENGTH_LONG).show();//短信内容
}
}
}
}
ps:android获取短信所有内容
publicclassGetMessageInfo{
List<MessageInfo>list;
Contextcontext;
MessageInfomessageInfo;
publicGetMessageInfo(Contextcontext){
list=newArrayList<MessageInfo>();
this.context=context;
}
//--------------------------------收到的短息信息----------------------------------
publicList<MessageInfo>getSmsInfos(){
finalStringSMS_URI_INBOX="content://sms/inbox";//收信箱
try{
ContentResolvercr=context.getContentResolver();
String[]projection=newString[]{"_id","address","person","body","date","type"};
Uriuri=Uri.parse(SMS_URI_INBOX);
Cursorcursor=cr.query(uri,projection,null,null,"datedesc");
while(cursor.moveToNext()){
messageInfo=newMessageInfo();
//-----------------------信息----------------
intnameColumn=cursor.getColumnIndex("person");//联系人姓名列表序号
intphoneNumberColumn=cursor.getColumnIndex("address");//手机号
intsmsbodyColumn=cursor.getColumnIndex("body");//短信内容
intdateColumn=cursor.getColumnIndex("date");//日期
inttypeColumn=cursor.getColumnIndex("type");//收发类型1表示接受2表示发送
StringnameId=cursor.getString(nameColumn);
StringphoneNumber=cursor.getString(phoneNumberColumn);
Stringsmsbody=cursor.getString(smsbodyColumn);
Dated=newDate(Long.parseLong(cursor.getString(dateColumn)));
SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd"+"\n"+"hh:mm:ss");
Stringdate=dateFormat.format(d);
//--------------------------匹配联系人名字--------------------------
UripersonUri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,phoneNumber);
CursorlocalCursor=cr.query(personUri,newString[]{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);
Stringname=localCursor.getString(localCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
longphotoid=localCursor.getLong(localCursor.getColumnIndex(PhoneLookup.PHOTO_ID));
longcontactid=localCursor.getLong(localCursor.getColumnIndex(PhoneLookup._ID));
messageInfo.setName(name);
//如果photoid大于0表示联系人有头像,如果没有给此人设置头像则给他一个默认的
if(photoid>0){
Uriuri1=ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);
InputStreaminput=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(SQLiteExceptione){
e.printStackTrace();
}
returnlist;
}
}
以上内容是小编给大家分享的Android开发获取短信的内容并截取短信,希望大家喜欢。