手动终止 javascript 线程

Manually kill the javascript thread

是否可以在 android 中终止线程 我看到有一个

Thread.currentThread().destroy();

然而,它已被弃用,仍然对我不起作用。我目前在中国,没有使用 VPN,所以无法读取 android dev,但我知道它在那里说插入到 webview 中的 javascript 将在单独的线程中 运行。

问题是即使 webview 和 fragment 被销毁,这个线程也没有被杀死。所以它继续脚本,即使我希望它是 aborted/stoped/destroyed (无论如何)。

想停止时调用mWebView.destroy();javascript。 Activity 销毁后停止播放音乐对我有用。我在 Activity 的 onDestroy() 中调用了该方法。

这是该方法的文档:

public void destroy ()

Added in API level 1 Destroys the internal state of this WebView. This method should be called after this WebView has been removed from the view system. No other methods may be called on this WebView after destroy.

更新:

我找到了另一个可行的解决方案。它的关键思想是如果你想停止前一个 url 中的 javascript,则加载另一个 url。因此,您可以在资产中放置一个空白 html 文件,并在您想要停止耗时 javascript 时加载它。代码如下:

appWebView.loadUrl("file:///android_asset/infAppPaused.html");

请参考post here.

更新 1: post.

中问题的最终解决方案

在 JavaScriptInterface 中添加一个检查状态的方法 class 并在处理循环期间调用该方法,如果状态不匹配则退出循环。然后,如果您在片段销毁时将状态更改为 "quit state",javascript 将停止。

这是代码示例:

private boolean webviewAlive = true;
public class JavaScriptInterface {

    @JavascriptInterface
    public boolean checkState() {
        return webviewAlive;
    }

}

// Init WebView 
mWebView.addJavascriptInterface(new JavaScriptInterface(),
        "HtmlViewer");

// To stop the javascript loop
webviewAlive = false;

// Call check state method in javascript loop
if(!window.HtmlViewer.checkState()){
    // break the javascript
}

尝试 Thread.currentThread().interrupt(); 然后将您的线程设置为空。

编辑

根据 javadocs,currentThread() 获取,好吧,如果 运行,我假设 "currently executing thread object" 获取您的线程。如果您想更具体地了解您正在使用的线程,您可以

    //get a reference
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

        }
    });

    //kill the thread
    t.interrupt();
    t = null;

编辑 哦,呃,我没注意到整个 "javascript into webview" 事情。我的错。你能 post 介绍一下你当前的实现吗?