action名称一致的BroadcastReceiver 的优先级

action名称一样的广播接收器都有权力接收到广播。但是其中优先级高的会先接收到广播。如果发送的广播属于有序广播( sendOrderedBroadcast() ),而不是无需广播( sendBroadcast() ),那么优先级高的接收器可以利用abortBroadcast()防止广播继续向同类广播接收器传播。

    <receiver
            android:name = ".MyReceiver">
            <intent-filter 
                android:priority="9">
                <action android:name = "包名.intent.action.Receiver"/>
           </intent-filter>
     </receiver>

     <receiver
            android:name = ".MyReceiver1">
            <intent-filter 
                android:priority="10">
                <action android:name = "包名.intent.action.Receiver"/>
            </intent-filter>
    </receiver>

从上面我们可以看到两个广播接收器的action是一样的,因此我们指定优先级priority。数值越大,优先级越高。因此首先接收到广播的是MyReceiver1。此时如果我们发送的广播属于有序广播( sendOrderedBroadcast() ),便可以在MyReceiver1中使用abortBroadcast()来中断MyReceiver接收广播。

@SuppressLint("NewApi") public class MainActivity extends Activity { SmsReceiver myReceiver; Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { test(); } }); } public void test(){ Cursor cursor = null; String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(this); Intent intent = new Intent(Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Sms.Intents.EXTRA_PACKAGE_NAME, this.getPackageName()); startActivity(intent); try { cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), new String[] { "_id", "address", "read" }, "read = ? ", new String[] {"0" }, "date desc"); if (cursor != null) { ContentValues values = new ContentValues(); values.put("read", "1"); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { Log.v("cky", "" + cursor.getInt(cursor.getColumnIndex("_id")) + " , " + cursor.getString(cursor.getColumnIndex("address"))); int res = getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=?", new String[] { "" + cursor.getInt(cursor.getColumnIndex("_id")) }); Log.i("cky","geng xin = "+res); } } intent = new Intent(Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); cursor = null; } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AidenWU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值