在演示广播接收者的两种注册方式时,出现了异常:动态注册电话拨号拦截的广播接收者没有反应。
广播接收者代码:
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("MyReceiver","onReceive"); Toast.makeText(context,"收到了一条广播",Toast.LENGTH_SHORT).show(); String outcall=getResultData(); SharedPreferences sp =context.getSharedPreferences("data",Context.MODE_PRIVATE); String num=sp.getString("number",null); if ((outcall.equals(num))) { setResultData(null); } } }主Activity代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private EditText input; MyReceiver myReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input=(EditText)findViewById(R.id.input); findViewById(R.id.save).setOnClickListener(this); //动态注册 myReceiver=new MyReceiver(); String action =Intent.ACTION_NEW_OUTGOING_CALL; Log.d("MainActivity",action); IntentFilter intentFilter=new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL); registerReceiver(myReceiver,intentFilter); } @Override public void onClick(View v) { switch (v.getId()) { //保存要拦截的号码 case R.id.save: { SharedPreferences sp=getSharedPreferences("data",MODE_PRIVATE); SharedPreferences.Editor editor=sp.edit(); editor.putString("number",input.getText().toString().trim()); editor.commit(); break; } } } @Override protected void onDestroy() { super.onDestroy(); //取消动态注册 unregisterReceiver(myReceiver); } }最开始怀疑是action写错了,可是上网查了很多资料,没有写错。静态注册是没有问题的,所以广播接收者的代码没有问题,一次次测试,都无法拦截外拨电话。
后来突然意识到一个问题:ACTION_NEW_OUTGOING_CALL外拨电话的广播是有序的还是无序的,是否是存在优先级的问题?
再次去网上查找资料:http://blog.csdn.net/Gaugamela/article/details/62046359,这篇博客给我解惑了。所以修改了广播接收者注册的代码,如下所示:
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL); intentFilter.setPriority(1000); registerReceiver(myReceiver,intentFilter);重新运行测试,还是不行,再改代码:
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL); intentFilter.setPriority(Integer.MAX_VALUE); registerReceiver(myReceiver,intentFilter);
终于可以了~~~
总结:广播接收者需要注意的问题:1.要接收的广播类型,是有序还是无序;2.广播接收者的优先级,范围是Integer.MIN_VALUE-Integer.MAX_VALUE;