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:
- 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.
- private BroadcastReceiver myBroadCastReceiver =new BroadcastReceiver()
- {
- @Override
- public void onReceive(Context context, Intent intent )
- {
- Log.d( "Broadcastreceiver: " + intent.getAction() + " package: "+intent.getPackage() + " @" + System.currentTimeMillis() );
- }
- };
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.
0 0
- Broadcast receiver Activity
- Android Activity& service&Broadcast receiver 生命周期
- Activity、Broadcast Intent Receiver、Service、Content Provider
- broadcast receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- Broadcast Receiver
- BroadCast Receiver
- Broadcast Receiver
- UVa 511 - Do You Know the Way to San Jose? [STL应用]
- [LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
- C++ private成员变量作用域的扩展
- 半透明的实现
- 关于linux内核container_of宏的理解
- Broadcast receiver Activity
- adb shell am & busybox
- 黑马程序员_Java中的运算符
- pthread_create() 返回 11
- adding animations - Using ViewPager for Screen Slides
- 蓝天碧水中国梦-总览(3)-中国节能减排目标
- thinkphp处理jQuery EasyUI form表单问题
- Machine Learning - VII. Regularization规格化 (Week 3)
- 重写viewgroup现实上下view滑动(修改版)