Board logo

Title: 要在 WebView 中打开指定的页面并在后台检测到 "ringringring" 字符时调用系统提示音,你可以使用以下步骤实现这个功能。 [Print this page]

Author: sky999    Time: 2024-10-7 22:53     Title: 要在 WebView 中打开指定的页面并在后台检测到 "ringringring" 字符时调用系统提示音,你可以使用以下步骤实现这个功能。

1. 设置 WebView 在你的活动中,设置 WebView,并添加 JavaScript 接口:

CODE:
[Copy to clipboard]
import android.media.MediaPlayer; import android.os.Bundle; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new WebAppInterface(), "Android"); webView.setWebViewClient(new WebViewClient()); // 加载指定的网页 webView.loadUrl("http://service.caffz.com:12345/mud/AbyssalSwamp/index/worldhouse.php"); // 开始定时检查 startChecking(); } private void startChecking() { new Thread(() -> { while (true) { runOnUiThread(() -> { webView.evaluateJavascript("document.body.innerText.includes('ringringring')", value -> { if (Boolean.parseBoolean(value)) { playSound(); } }); }); try { Thread.sleep(1000); // 每秒检查一次 } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } private void playSound() { MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, android.R.raw.notification); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(mp -> mp.release()); } public class WebAppInterface { @JavascriptInterface public void playSound() { playSound(); } } }
2. 权限设置 确保在 AndroidManifest.xml 中添加必要的权限:

CODE:
[Copy to clipboard]
<uses-permission android:name="android.permission.INTERNET"/>
[ 本帖最后由 sky999 于 2024-10-7 22:54 编辑 ]




Welcome AbyssalSwamp (http://service.caffz.com:12345/mud/AbyssalSwamp/index/) caffz.com