简体   繁体   中英

How to keep webview running in foreground service after pressing home button in android?

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 ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM