一、Activity與BroadcastReceiver通信
1)新建一個(gè)BroadcastReceiver,在MainActivity里通過sendBroadcast方法發(fā)送數(shù)據(jù)
2)在MyReceiver類中重寫onReceive方法,用參數(shù)intent接收數(shù)據(jù)
二、BroadcastReceiver注冊和注銷
1)先在MyReceiver類中定義一個(gè)ACTION常量
2)在MainActivity中創(chuàng)建Intent實(shí)例,此時(shí)就不能用顯示的方法創(chuàng)建了,要用隱示的方法通過ACTION的值來實(shí)例化
3)在MainActivity中定義一個(gè)MyReceiver的對象,初始化為null。在用registerReceiver方法時(shí)要確保MyReceiver的對象為空,在用unregisterReceiver方法時(shí)確保MyReceiver對象不為空
三、BroadcastReceiver優(yōu)先級(jí)
當(dāng)有多個(gè)廣播接收器的時(shí)候,他們的ACTION一致,想設(shè)置誰先收到就可以在AndroidManifest.xml文件中的intent-filter中添加priority,數(shù)字高的先接收
當(dāng)優(yōu)先級(jí)高的接收到了想阻止后面的廣播接收器接收的話,就需要在相應(yīng)的接收器里用abortBroadcast方法停止廣播,但阻止的話在MainActivity里發(fā)送廣播的方法就不能用sendBroadcast了,不然會(huì)出現(xiàn)異常,要用sendOrderedBroadcast方法
sendOrderedBroadcast(i,null);