tags:

views:

523

answers:

2

I am writing a home screen widget and want to update the home screen widget when the device orientation changes from portrait to landscape or the other way. How can I make it?

Currently, I tried to reigster to CONFIGURATION_CHANGED action like the code below, but the Android didn't allow me to do that by saying "IntentReceiver components are not allowed to register to receive intents". Can someone help me? Thanks.

public class MyWidget extends AppWidgetProvider {

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        this.registerReceiver(this, new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }
A: 

You probably shouldn't need to do this. You can use layout and layout-land folders to provide different layouts in each orientation via xml without manually detecting rotation. However, you shouldn't do anything functionally different in each orientation as a lot of devices can't rotate the homescreen and whatever features you put in will be inaccessible for them.

jqpubliq
+1  A: 

While I sorta agree with jqpubliq's answer, so long as you think about what you're doing and design matters properly, you are welcome to implement different layouts for different orientations. It's just going to be complicated.

The error message you received should be self-explanatory: BroadcastReceivers (like AppWidgetProvider) cannot register for other broadcasts. After all, a manifest-registered BroadcastReceiver instance should be in memory for milliseconds, not forever.

Hence, to implement this logic, you will need to:

  1. Create an IntentService that handles the actual app widget updates, and have your AppWidgetProvider delegate its work to that. Here is an example.
  2. Create a separate BroadcastReceiver implementation, registered in the manifest to receive CONFIGURATION_CHANGED broadcast Intents.
  3. Have that new BroadcastReceiver also use the IntentService (e.g., call startService()).
  4. Have IntentService handle the updates for both orientations, emanating from both receivers.
CommonsWare
Thanks for your replay. Very helpful.There is one problem with the third step in your suggestion. The Android spec said about ACTION_CONFIGURATION_CHANGED: "You can not receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver(). "That's the reason I tried to use registerReceiver in my AppWidgetProvider. Any thoughts?
Oops. Forgot about that. That puts more emphasis on jqpubliq's answer, then. To receive that broadcast, you would need to keep a service hanging around in memory indefinitely. That's bad for business, not to mention inevitably ineffective -- either Android or your user will kill off your service, like it or not.
CommonsWare