Broadcast receiver Activity

来源:互联网 发布:75团淘宝兼职399入会 编辑:程序博客网 时间:2024/04/28 14:54

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