WebView 在后台工作

WebView working in background

我制作了在后台观看 YouTube 的应用。当我关闭屏幕时它正在工作,但是当我最小化应用程序时它停止了。我用服务做到了。你有什么想法如何正确地做到这一点吗?

有我的代码:

public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       MainActivity.displayYoutubeVideo.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        WebSettings webSettings = MainActivity.displayYoutubeVideo.getSettings();
        webSettings.setJavaScriptEnabled(true);
        MainActivity.displayYoutubeVideo.loadUrl("https://www.youtube.com/feed/trending");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

在后台观看 Youtube 没有任何意义。在后台时,没有什么是“可观看的”。 activity 不再有效。 Android Dev. Guide

As the user begins to leave the activity, the system calls methods to dismantle the activity. In some cases, this dismantlement is only partial; the activity still resides in memory (such as when the user switches to another app), and can still come back to the foreground.

If the user returns to that activity, the activity resumes from where the user left off. The system’s likelihood of killing a given process—along with the activities in it—depends on the state of the activity at the time.

所以你所面临的行为是有意设计的。

你建议你通过服务来做这件事也是个坏主意。首先,服务旨在帮助您 运行 长时间的后台进程,而不会冻结 UI。但是你希望 UI 到 运行 在没有人注意的时候出现在后台。

其次,服务在最近的 android 版本中一直存在问题,官方不鼓励使用,并且前景黯淡。 Work Manager 鼓励后台任务。

Do you have any ideas how to do it right?

我不知道你具体是怎么做到的,所以我会给出一般的看法。 Android 将管理您的活动生命周期,您负责数据。如果您以某种方式从 youtube 获取数据,则可以将它们存储在 LiveData 对象中,这样当 Activity 处于活动状态时,您可以从上次离开的地方继续。

我不建议您尝试以某种方式在后台播放视频。完全没有意义!