Search code examples
androidserviceandroid-broadcastreceiver

How can I invoke a method of a service class from a broadcastReceiver ?


I'm implementing a broadcast receiver to check connectivity. I want to invoke method of the service from the onReceive method of the receiver.

How I can invoke method of a service from a receiver ?

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if ((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)
            || (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)))) {
        boolean status = NetworkUtil.isOnline(context);

        if (status) {
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
            int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);


            //  Here I want to invoke a method in the service to consume api and check new results ;

            updateAllWidgets(context, appWidgetManager, appWidgetIds);
        }

        Toast.makeText(context, "Network change   " + msg, Toast.LENGTH_SHORT).show();

    }
} 

Solution

  • I resolve this problem by following those steps:

    1. I identify the tasks of the service (consume api , store data ...) and when they are done I stop the service .
    2. When the receiver notify me that the Wifi is disabled , I stop the current service and when It notify me that the Wifi is enabled, I start the service again to redo all the tasks.