Android App Building (Java) - 为什么 Android Studio 中的 "onWindowVisibilityChanged" 不起作用?



我正在尝试阻止WebView媒体内容在用户退出或屏幕锁定时停止。

我在这里遵循这个解决方案,但它仍然阻止媒体播放。

WebView媒体内容在屏幕被锁定时停止(activity's onStop被调用)

如何让WebView在后台播放视频或音频?

我的代码的主要部分是这样的:
public class WebApp extends AppCompatActivity {
WebView webView;
WebSettings webSettings;
String ua = "Mozilla/5.0 (Linux; Android 10; Google Pixel 4 Build/QD1A.190821.014.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.108 Mobile Safari/537.36";
public static String url = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Objects.requireNonNull(getSupportActionBar()).hide();
getWindow().setStatusBarColor(getColor(R.color.black));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_nitter);


webView = findViewById(R.id.webview);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyChrome());
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
public class MyWebView extends WebView {
public MyWebView(Context context) {
super(context);
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
if (visibility != View.GONE) super.onWindowVisibilityChanged(visibility);
}
}
@Override
public void onBackPressed(){
if(webView.canGoBack())
{
webView.goBack();
}
else
{
webView.clearHistory();
super.onBackPressed();
}
}

有人能告诉我我做错了什么,即使我认为我遵循了正确的解决方案?谢谢你。

当我研究同样的问题时,我可以这样解决它。https://stackoverflow.com/a/14055346

"activity_main.xml"尝试:

<org.example.myapp.MyWebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>