1

I have a widget and I would like to check if the screen is off or on.

I can't use PowerMananger.isScreenOn because I want to support Android 1.5/1.6 .

So I tried to register SCREEN_ON/SCREEN_OFF actions in the manifest but that doesn't work. Seems like only registerReceiver works for those intents. (Android - how to receive broadcast intents ACTION_SCREEN_ON/OFF?)

The question is, where should I register my widget?

I can't register the screen intents receiver from my widget because you can't call registerReceiver from another BroadcastReceiver that is stated in the manifest.

I thought about calling it in the onCreate of my configuration activity.

The problem is that I don't call unregisterReceiver, so I get an exception for a leak.

Is there any other solution to this?

Thanks.

Community
  • 1
  • 1
Ran
  • 4,117
  • 4
  • 44
  • 70

2 Answers2

2

My solution is to start a service in the public void onReceive(Context context, Intent intent) method in the AppwidgetProvider subclass. Like:

        if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_ENABLED)) {
        Intent listenerService=new Intent(context,ScreenMoniterService.class);
        startService(listenerService);
        return;
    }

Then in the public void onCreate() method of this service, register the BroadcastReceiver and in the public void onDestroy() method, unregister it. Of course, you should stop that service when all of the appwidget are deleted.

        if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_DISABLED)) {

        Intent listenerService=new Intent(context,ScreenMoniterService.class);
        stopService(listenerService);
        return;
    }
Huang
  • 4,812
  • 3
  • 21
  • 20
  • so the service has to run as long as the widget is running? – Ran Nov 19 '11 at 14:05
  • Yes. This is what I am doing with my appwidget. Because the AppWidgetProvider is essentially a BroadcastReceiver, the widget itself is just running within the onReceive() method, so I thinks it had better to start a service. Please see the accepted answer in this post: http://stackoverflow.com/questions/6481625/android-widget-lifecycle – Huang Nov 19 '11 at 14:19
0

registerReceiver:

final IntentFilter bcFilter = new IntentFilter(); bcFilter.addAction(Intent.ACTION_SCREEN_ON); bcFilter.addAction(Intent.ACTION_SCREEN_OFF); context.getApplicationContext().registerReceiver(this, bcFilter);

unregisterReceiver:

context.getApplicationContext().unregisterReceiver(this);

(Just at AppWidgetProvider!)