0

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?

wodzu
  • 3,004
  • 3
  • 25
  • 41
  • then let me rephrase this: I want that app widget always to play a sound, when it is being clicked. If a service isn't always reachable, means running, the widget could fail to play the sound, would't it? I don't want to use a `IntentService`, since it would be killed after every playback and then recreated on the next one. – wodzu Aug 06 '13 at 19:40
  • What do you think is wrong with starting an IntentService every time? If I installed your app and found that it had a permanent service running, I'd leave a bad review and then uninstall it. – Khantahr Aug 06 '13 at 20:06
  • disposing and initializing of a new `MediaPlayer` intance just to play a sound seems to be extremely recource-hungry – wodzu Aug 06 '13 at 20:46
  • You should try reading the documentation on [MediaPlayer](http://developer.android.com/guide/topics/media/mediaplayer.html). It tells you to release it when you're not using it because it can consume a lot of resources. Just use an IntentService and recreate it every time. – Khantahr Aug 06 '13 at 21:55

1 Answers1

4

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491