If you want to catch a broadcasted intent on an Activity, you may get the following error:
-
02 -22 08 :18 :46.874 : E /AndroidRuntime (276 ) : java. lang. RuntimeException :Unable to instantiate receiver com. helloandroid. broadcasttest. BroadcastTestActivity$MyBroadcastReceiver :
-
...
-
java. lang. InstantiationException :com. helloandroid. broadcasttest. BroadcastTestActivity$MyBroadcastReceiver
-
-
-
...
-
-
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.
No need to set this receiver in the manifest xml file, register it in the activity's onresume method and unregister in the onpause:
-
public void onResume ( ) {
-
super. onResume ( ) ;
-
....
-
registerReceiver (myBroadcastReceiver, newIntentFilter ( "your.custom.BROADCAST&qu
ot; ) ) ; -
}
-
-
public void onPause ( ) {
-
super. onPause ( ) ;
-
...
-
unregisterReceiver (myBroadcastReceiver ) ;
-
}
-
...
-
}
Thats all, the receiver will catch the broadcasts, if the activity is on the screen.
To broadcast custom intents, use the following method:
-
Intent broadCastIntent = new Intent ( ) ;
-
-
-
-
broadCastIntent. setAction ( "your.custom.BROADCAST&qu
ot; ) ; -
broadCastIntent. setPackage ( "com.helloandroid.broadca
sttest" ) ; -
-
ApplicationObject. applicationContext. sendBroadcast (broadCastIntent ) ;
-
-
Log. d ( "Broadcast sent" ) ;
The setPackage() method set an explicit application package name that limits the components the Intent will resolve to.