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

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 Contextobjects. The main difference is scope or lifetime.

The application's Context (that you can get with Activity.getApplicationContext() orContext.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 inonReceive(). This Context has a very short lifetime (it is destroyed immediately after theonReceive() 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().

你可能感兴趣的:(exception)