Home > Software design >  how to run an android foreground service in cordova?
how to run an android foreground service in cordova?

Time:10-09

First, I've implemented a native android app in order to get familiar with Android's background tasks and foreground services. At some point I had a working foreground service notification app - fine.

        // native Android:
        Intent runningIntentService = new Intent(getApplicationContext(), ForegroundService.class);
        stopService(runningIntentService);
        startService(runningIntentService);   // the onCommandStart is being executed.

Then I compiled everything as a cordova plugin, but in the end, the service's onCommandStart method is not called. What to do in cordova in order to start the service?

        // Cordova:
        try {
           Intent runningIntentService = new Intent(cordova.getActivity().getApplicationContext(), ForegroundService.class);
           Log.d("test", "#1");  // gets logged
           cordova.getActivity().stopService(runningIntentService);
           Log.d("test", "#2");  // gets logged
           cordova.getActivity().startService(runningIntentService); // the onCommand is not being executed.
           Log.d("test", "#3");  // gets logged
        } catch (Exception e) {
           Log.e("test","Error: "   e.toString());  // nothing is catched.
        }

CodePudding user response:

My mistake was setting a wrong path in the plugin.xml for the package's android service name:

        <service android:name=".ForegroundService"/>  <!-- wrong -->
        <service android:name="com.package.example.ForegroundService"/>  <!-- right -->
  • Related