22 接受收到短信广播
- 权限:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
意图
<!-- 短信的广播Action -->
<receiver android:name=".MySmsReceiver">
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
结构:
MainActivity.java
package com.qf.day22_broadcastreceiver_demo8;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MySmsReceiver.java
补充说明:因为当你发一条短信140个字符(70汉子)以上时会分为两条短息发送 所以收到是数组
SmsMessage.createFromPdu((byte[])pdus[i]) 在API23过时
package com.qf.day22_broadcastreceiver_demo8;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class MySmsReceiver extends BroadcastReceiver{
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
/**
* pdus:承载一条短信的所有内容的载体 一条短信 可以有140 字节
*/
Bundle bundle = intent.getExtras();
Object[]pdus = (Object[]) bundle.get("pdus");
//获取短信数组
SmsMessage[] smsMessages = new SmsMessage[pdus.length];
/*//高版本过时
//将pdus里内容转换成SmsMessage
for(int i=0;i<pdus.length;i++){
smsMessages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}*/
//高版本
String format2 = intent.getStringExtra("format");
//将pdus里内容转换成SmsMessage
for(int i=0;i<pdus.length;i++){
//高版本过时
smsMessages[i] = SmsMessage.createFromPdu((byte[])pdus[i],format2);
}
//获取电话号
String num = smsMessages[0].getOriginatingAddress();
//获取发送短信的时间戳
long t = smsMessages[0].getTimestampMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String time = format.format(new Date(t));
//获取短信的所有内容
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<smsMessages.length;i++){
stringBuffer.append(smsMessages[i].getDisplayMessageBody());
}
String body = stringBuffer.toString();
Log.e("AAA", "==num=="+num+"==time=="+time+"==body=="+body);
}
}