1

I am loading an url in webview which plays some audio song. When user presses the home button, then the audio stops after some time(Probably because activity is going in stopped state).

Well, I think service might solve my problem. But How can I keep the song playing i.e Webview in foreground and show it on notification bar in service.

Edit:- I don't want to load the URL again because doing that will again go to home page of the website. I think this can be done using foreground Service. But I am not getting how can I save the state of the webview and keep it running from that state using foreground Service.

Shubh.J
  • 145
  • 1
  • 2
  • 12
  • Do you meaning keeping that webview that is playing the song at the background and showing it on the notification bar? – Angus Oct 26 '19 at 09:05
  • Possible duplicate of [Android: Using WebView outside an Activity context](https://stackoverflow.com/questions/18865035/android-using-webview-outside-an-activity-context) – tynn Oct 26 '19 at 10:25
  • @angus you are absolutely right. I think it can be done by using foreground Service. But I am not getting how can I do that! – Shubh.J Oct 26 '19 at 13:44
  • @tynn The link you have mentioned is loading the webview again using loadurl which I don't want. Because it will start the song again from the beginning. – Shubh.J Oct 26 '19 at 13:46
  • Have you found a solution? – Artur Dumchev Mar 25 '20 at 08:58
  • @ArturDumchev No I have not. Have you? – Shubh.J Sep 14 '20 at 00:17

1 Answers1

0

The only solution I tried myself is to attach webview to a window with 0 size (to make it invisible):

val params = WindowManager.LayoutParams(
    0, 0, TYPE_APPLICATION_OVERLAY, FLAG_NOT_FOCUSABLE or FLAG_NOT_TOUCHABLE, PixelFormat.RGBA_8888
)
(context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).addView(webview, params)

You can perform this code inside your foreground service and remove webview from window when app goes foreground:

windowManager.removeViewImmediate(webivew)

You may invoke this attach/detach code inside onStart/onStop of your activity (or onCreate/onDestroy of your Service, but you will have to close the service when app goes foreground). You only need the foreground service to save your app from being killed by android system.

Another point to think off — you should not create your webview in activity (to prevent memory leak) as your webview has different lifecycle. One way is to create your webview inside Application (with it's context) and inject it inside activity.

Artur Dumchev
  • 1,252
  • 14
  • 17