Broadcast receiver Activity

If you want to catch a broadcasted intent on an Activity, you may get the following error:

  1. 02 -22 08 :18 :46.874 : E /AndroidRuntime (276 ) : java. lang. RuntimeException :Unable to instantiate receiver com. helloandroid. broadcasttest. BroadcastTestActivity$MyBroadcastReceiver :
  2. ...
  3. java. lang. InstantiationException :com. helloandroid. broadcasttest. BroadcastTestActivity$MyBroadcastReceiver
  4.  
  5.  
  6. ...
  7.  
  8. 02 -22 08 :18 :46.874 : E /AndroidRuntime (276 ) : Caused by :java. lang. InstantiationException :com. helloandroid. broadcasttest. BroadcastTestActivity$MyBroadcastReceiver

This is because you can't instantiate a receiver in an inner class.

Instead of inner receiver, you can manually instantiate a broadcast receiver yourself in the activity.

  1.          private BroadcastReceiver       myBroadCastReceiver      = new BroadcastReceiver ( )
  2.                  {
  3.  
  4.                                 @Override
  5.                                  public  void onReceive ( Context context, Intent intent  )
  6.                                  {
  7.                                                 Log. d (  "Broadcastreceiver: "  + intent. getAction ( )  +  " package: " +intent. getPackage ( )  +  " @"  +  System. currentTimeMillis ( )  ) ;
  8.                                  }
  9.                  } ;

No need to set this receiver in the manifest xml file, register it in the activity's onresume method and unregister in the onpause:

  1.      public  void onResume ( )  {
  2.          super. onResume ( ) ;
  3.         ....
  4.          registerReceiver (myBroadcastReceiver,  newIntentFilter ( "your.custom.BROADCAST" ) ) ;
  5.      }
  6.  
  7.      public  void onPause ( )  {
  8.          super. onPause ( ) ;
  9.         ...
  10.          unregisterReceiver (myBroadcastReceiver ) ;
  11.      }
  12.     ...
  13. }

Thats all, the receiver will catch the broadcasts, if the activity is on the screen.

To broadcast custom intents, use the following method:

  1.                 Intent broadCastIntent  =  new Intent ( ) ;
  2.  
  3.                
  4.  
  5.                 broadCastIntent. setAction (  "your.custom.BROADCAST"  ) ;
  6.                 broadCastIntent. setPackage ( "com.helloandroid.broadcasttest"  ) ;
  7.                
  8.                 ApplicationObject. applicationContext. sendBroadcast (broadCastIntent  ) ;
  9.  
  10.                 Log. d (  "Broadcast sent"  ) ;

The setPackage() method set an explicit application package name that limits the components the Intent will resolve to.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值