【问题标题】:Is it possible to call javascript function and access localStorage on "BOOT_COMPLETED" broadcast? (android)是否可以在“BOOT_COMPLETED”广播中调用 javascript 函数并访问 localStorage? (安卓)
【发布时间】:2021-08-29 08:36:44
【问题描述】:

我正在开发移动网络应用程序。该应用程序将所有数据保存到 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()");
    }
}

【问题讨论】:

    标签: android reboot


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢你,亚历克斯!我不知道这样的 10 秒规则。我可能会选择 SharedPreference。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多