您的位置:首页 > 移动开发 > Android开发

Exception android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to bind to services(广播中的异常)

2012-10-29 17:47 1526 查看
This question is over a year old and is definitely long and complicated and the English language is difficult to understand. However, it still probably deserves some kind of answer.

If I understand, you are basically asking for the difference between the different Android
Context
objects. The main difference is scope or lifetime.

The application's Context (that you can get with
Activity.getApplicationContext()
or
Context.getApplicationContext()
has a lifetime of your entire application. The application Context is created when your application (or parts of it) are started. It lives (more or less) forever.

An activity's Context is created when that Activity is created and goes away when that activity is destroyed. If you are doing anything with the UI, you need to do that using the activity's Context so that when the activity is destroyed, those things that are related to that activity are also cleaned up.

There are other Contexts like the one you get in a BroadcastReceiver or an AppWidgetProvider in
onReceive()
. This Context has a very short lifetime (it is destroyed immediately after the
onReceive()
method returns). Therefore you can only do limited things with this Context.

You want to register a Receiver to listen for the broadcast Intents you are interested in. You cannot do this with the Context you get in
onReceive()
because that Context has a short lifetime and the listener has to be linked to something. In this case you can use the application's Context to link the listener to. This works, but you need to realize that you've created some objects that will never go away because they are always active. At least you should make sure that you clean this up when the user deletes your widget from his home screen by removing the listener using
unregisterReceiver()
.

就是要多一步 context.getApplicationContext().
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐