Search code examples
androidreboot

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


I'm developing mobile web app. The app saves all data to html5 localStorage include alarm data. Since alarms be cleared after device reboot, I should re-register alarm after reboot.

I tried to find way about to access localStorage on onReceive of BroadcastReceiver, but I couldn't. Is there a way to call javascript function on "BOOT_COMPLETED" broadcast? If not, I think I should save data to 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()");
    }
}

Solution

  • It depends what you are trying to accomplish and how long that is going to take. According to the documentation, BroadcastReceivers should not run for more than 10 seconds. Because of that, running any javascript code or doing anything that might end up being unresponsive (http connections in general) is a bad idea.

    On an other note, you cannot call any Javascript code without having a WebView using nothing but pure Android. There are libraries that allow you to do it without a WebView (such as QuickJs). You might want to have a look at those or see if you can create a WebView programmatically and using that instead. That feels like a hack more than a proper solution.

    Your solution for storing the data and using it on a later time sounds like the best approach.