标签:extra private VID tco span his equals 短信 注意
这里我用的android studio版本是3.3的
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- <receiver -->
<!-- android:name=".SMSReceiver" -->
<!-- android:enabled="true" -->
<!-- android:exported="true"> -->
<!-- <intent-filter android:priority="20"> -->
<!-- <action android:name="android.provider.Telephony.SMS_RECEIVED"/> -->
<!-- </intent-filter> -->
<!-- </receiver> -->
我用的是动态注册广播,这里注释掉
直接上广播类SMSReceiver的代码public String msgBody="";
public String originatingAddress="";
Context context;
public SMSReceiver(Context context){
this.context=context;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")) {
//获取短信内容,有可能一次发来多条短信
Object[] objects = (Object[]) intent.getExtras().get("pdus");
for (Object obj : objects) {
//获取短信对象
SmsMessage msg = SmsMessage.createFromPdu((byte[]) obj);
//获取短信内容
msgBody = msg.getDisplayMessageBody();
//获取发信人的电话号码
originatingAddress = msg.getOriginatingAddress();
Log.i("wk", "短信内容==>" + msgBody + " 来自==>" + originatingAddress);
Toast.makeText(context,"短信内容==>" + msgBody + " 来自==>" + originatingAddress,Toast.LENGTH_SHORT).show();
}
}
}
SMSReceiver smsReceiver=new SMSReceiver(SMSActivity.this);
//动态注册广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver,intentFilter);
/**
* * 检查申请短信权限
* */
private void checkSMSPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
//未获取到读取短信权限
Toast.makeText(this,"未获取权限",Toast.LENGTH_SHORT).show();
// 向系统申请权限
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS}, REQ_CODE_CONTACT);
} else
{
query();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//判断用户是否,同意 获取短信授权
if (requestCode == REQ_CODE_CONTACT && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//获取到读取短信权限
query();
} else {
Toast.makeText(this, "未获取到短信权限", Toast.LENGTH_SHORT).show();
}
}
//根据之前在广播类公有属性短信内容和短信来源,在activity界面可以直接获取,并读取显示
//显示最近一条信息
private void dispLast(){
String msg=smsReceiver.msgBody;
String originatingAddress=smsReceiver.originatingAddress;
edit_sms.setText("短信内容==>" + msg + " 来自==>" + originatingAddress);
}
标签:extra private VID tco span his equals 短信 注意
原文地址:https://www.cnblogs.com/HYV587/p/11794932.html