我的应用中有一个BroadcastReceiver
,它在AndroidManifest.xml
中定义如下:
<receiver android:name=".receiver.MyTaskReceiver">
<intent-filter>
<action android:name="xxx.xxx.xxx" />
</intent-filter>
</receiver>
这是MyTaskReceiver
代码:
public class MyTaskReceiver extends BroadcastReceiver {
private ReceiverListener listener ;
@Override
public void onReceive(Context context, Intent intent) {
//do general things
if(listener != null) {
listener.received(); //do special things if the listener is setted up.
}
}
public void setListener(ReceiverListener listener) {
this.listener = listener;
}
public interface ReceiverListener {
void received();
}
}
当接收者有意图时,我会先做一些一般的事情,比如保存数据......
但是如果向用户显示指定的活动,我需要更改活动的视图,因此我使用ReceiverListener
来执行此操作。将听众设置为MyTaskReceiver
中的onCreate
,并在null
中设置onDestroy
。
然后出现了一个问题,如何获取MyTaskReceiver
的实例以便我可以设置一个监听器呢?
或者还有其他方法可以达到我的目的吗?
感谢。
答案 0 :(得分:5)
您可以在活动中注册接收器,如下所示:
private void registerBroadcastReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(xxx.xxx.xxx);
registerReceiver(this.broadcastReceiver, intentFilter);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
//do whatever need to be done
}
};
希望它有所帮助! :)
请记得取消注册您的接收者(例如在onDestroy()
)
unregisterReceiver(this.broadcastReceiver);