Ran
Ran

Reputation: 4157

Getting SCREEN_ON and SCREEN_OFF intents from a widget

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.

Upvotes: 1

Views: 1305

Answers (2)

user3026340
user3026340

Reputation: 1

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!)

Upvotes: 0

Huang
Huang

Reputation: 4842

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;
    }

Upvotes: 2

Related Questions