wodzu
wodzu

Reputation: 3172

What is the best way to let an app widget communicate with a service

I want my AppWidget (homescreen widget) to communicate with a Service, when the user presses a Button on it. That Service needs to be permanently running as long as the appWidget lives. As far as I know the only way to react on a widget's onClick event is to send PendingIntents via broadcasts. Currently I'm receiving these at my MainActivity, which forwards it to the running Service.

So actually I'm using my MainActivity as some kind of proxy for my widget's incoming events. Is this the right way? I would prefer to communicate with my Service directly - is this possible?

Upvotes: 0

Views: 1275

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006604

That Service needs to be permanently running as long as the appWidget lives

This is an anti-pattern in Android. It's also effectively impossible as a result. If you want reliable results and users not attacking you with task killers, redesign your app to not require an everlasting service.

As far as I know the only way to react on a widget's onClick event is to send PendingIntents via broadcasts.

There are three factory methods on PendingIntent: getActivity(), getService(), and getBroadcast(), to have the PendingIntent perform startActivity(), startService(), and sendBroadcast(), respectively.

I would prefer to communicate with my Service directly - is this possible?

Use a getService() PendingIntent instead of a getActivity() or getBroadcast() PendingIntent.

Upvotes: 4

Related Questions