Rumah > Soal Jawab > teks badan
按照书里面所讲,建了一个内部类用于接受系统发出的SMS_RECEIVED广播。通过代码进行注册,并设置了最高优先级。同时模拟器里手动打开了应用的权限,允许接受短信。
但问题是onReceive方法怎么也执行不到,也就是说接收器压根就没收到广播,真机里也没法收到广播(Android5.1);
以下是代码:
package com.example.smstest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView sender;
private TextView content;
//private Button send_broad;
private IntentFilter receiveFilter;
private MessageReceiver messageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activiry_main);
sender = (TextView) findViewById(R.id.sender);
content =(TextView) findViewById(R.id.content);
//send_broad=(Button) findViewById(R.id.broad);
receiveFilter = new IntentFilter();
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
//receiveFilter.addDataScheme("sms");
receiveFilter.setPriority(1000);
messageReceiver = new MessageReceiver();
registerReceiver(messageReceiver, receiveFilter);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(messageReceiver);
}
class MessageReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
Log.d("fuck", "fuck!!!!");
Toast.makeText(MainActivity.this, "You got a message", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage messages = null;
for (Object object : pdus){
messages = SmsMessage.createFromPdu((byte[]) object, android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
}
String address = messages.getOriginatingAddress();
sender.setText(address);
content.setText(messages);
}
}
}
提取短信内容的部分根据新的api有所不一样,但是不影响接受广播。
可以确定的是:Mainfest中声明过 android.permission.RECEIVE_SMS 权限;
广播接收器已经注册过;
应用的权限也打开了;
但无论如何就是接受不到广播,百度无果,大都是说权限,有个说道看schema,尝试无果,优先级设为1000,尝试无果,难道是系统默认的短信应用拦截了这个广播?我想也不应该,系统默认应用有自己的广播为什么要拦截其他广播。苦思了一晚上没有结果,希望有大牛给解答,感激万分;