2

我正在从我的一个班级发送广播:

    // Sending broadcast from my db helper constructor
    public DBHelper(Context ctx){
    this.ctx = ctx;
    Intent intent = new Intent();
    intent.setAction("custom.alert.abc");
    intent.putExtra("key",77);ctx.sendBroadcast(intent);




    //registering the broadcast in one of my activities oncreate
     IntentFilter alaramfilter = new IntentFilter();
    alaramfilter.addAction("custom.alert.abc");
     registerReceiver(alarmreceiver, alaramfilter); 

    //and declaring it
    private final BroadcastReceiver alarmreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    System.out.println("Broadcast received inside on receive");
    final String action = intent.getAction();
    if(action.equals("custom.alert.abc")) {
        Log.d("CPSnippetMain","My custom broadcast called");
        try {
             System.out.println("Broadcast received");
         } catch (Exception e) {
            e.printStackTrace();
        }
   }
}
};

问题是,尽管调用了构造函数并发送了广播,但未调用 onreceive。

任何帮助表示赞赏。

4

2 回答 2

3

sendbroadcast你和register重要的顺序。首先注册然后做一个sendBroadcast。

于 2012-09-25T18:09:37.497 回答
0

注册广播

private BroadcastReceiver receiver_;

@Overrride
public void onCreate(Bundle savedInstanceState){



 IntentFilter filter_data = new IntentFilter();
 filter_data .addAction("SOME_ACTION");


 receiver_= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
  //do something based on the intent's action
}
 }

 registerReceiver(receiver_, filter_data );

并在销毁方法中取消注册接收器

unregisterReceiver(receiver_);

于 2012-09-25T18:27:44.800 回答