是否可以在 "BOOT_COMPLETED" 广播中调用 javascript 函数并访问 localStorage? (android)

Is it possible to call javascript function and access localStorage on "BOOT_COMPLETED" broadcast? (android)

我正在开发移动网络应用程序。该应用程序将所有数据保存到 html5 localStorage,包括警报数据。由于设备重启后警报会被清除,所以我应该在重启后重新注册警报。

我试图找到在 BroadcastReceiver 的 onReceive 上访问 localStorage 的方法,但我做不到。有没有办法在“BOOT_COMPLETED”广播中调用 javascript 函数? 如果没有,我想我应该将数据保存到SharedPreference。

public class DeviceBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("DeviceBootReceiver", "DeviceBootReceiver.onReceive");

        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            // like this
            MainActivity.this.getWebViewInterface().reRegisterAllAlarm();
        }
    }
}

public class WebViewInterface {

    private Context mContext;
    private WebView mWebView;

    public WebViewInterface(Context context, WebView webView) {
        mContext = context;
        mWebView = webView;
    }

    public void reRegisterAllAlarm() {
        mWebView.loadUrl("javascript:reRegisterAllAlarm()");
    }
}

这取决于您想要完成什么以及需要多长时间。根据 to the documentation,BroadcastReceivers 不应 运行 超过 10 秒。因此,运行使用任何 javascript 代码或做任何可能最终无响应的事情(通常是 http 连接)是一个坏主意。

另一方面,如果 WebView 只使用纯 Android,则不能调用任何 Javascript 代码。有些库允许您在没有 WebView 的情况下执行此操作(例如 QuickJs)。您可能想看看那些,或者看看您是否可以以编程方式创建 WebView 并改用它。这感觉更像是一个 hack,而不是一个合适的解决方案。

您存储数据并在以后使用它的解决方案听起来是最好的方法。