Skip to content Skip to sidebar Skip to footer

Android Call Method In Service From Activity

I want to call a method in a Service object from an Activity object, however I have found it is not possible to call the method from the MainActivity normally. I hope my code expla

Solution 1:

The accepted answer isn't wrong but very unnecessarily complex.

Add this to the activity:

Intent i = newIntent(this, SERVICE_NAME.class);
i.setAction("YOUR_ACTION");
startService(i);

and this to the Service:

@Override
publicintonStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction() != null && intent.getAction().equals("YOUR_ACTION")) {
        invokeServiceMethod(); // here you invoke the service method
    }
    return START_STICKY; // or whatever floats your boat
}

Solution 2:

A simpke way is to send an intent from Activity and handle it in onStartCommand() method of Service. Don't forget to supply intent with right action/extras & check that in onStartCommand()

EDIT:

Activity:

Add a private class:

privateclassCustomReceiverextendsBroadcastReceiver {

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_CUSTOM_ACTION)) {
            doCustomAction();
        }
    }
}

Add a private field:

private CustomReceiver mCustomReceiver;

In onCreate() method:

mCustomReceiver = new CustomReceiver();

In onResume() or other lifecycle method:

IntentFilter filter=new IntentFilter(ACTION_CUSTOM_ACTION);   
registerReceiver(mCustomReceiver , filter);

In onPause() or other paired(to previous step) lifecycle method

unregisterReceiver(mCustomReceiver );

In activity whenever you wish to call use Service methods:

startService(new Intent(SOME_ACTION));

In Service:

@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {

    if (intent == null) {
        return START_STICKY;
    }

    Stringaction= intent.getAction();

    if (action == null) {
        return START_STICKY;
    } elseif (action.equals(SOME_ACTION)) {
                    invokeSomeServiceMethod();// here you invoke service method
            }

    return START_STICKY;
}

Note, that START_STICKY may be not the best choice for you, read about modes in documentation.

Then, when you want to notify activity that you've finished, call:

startActivity(ACTION_CUSTOM_ACTION);

This will trigger broadcast reciever where you can handle finish event.

Seems that that's a lot of code, but really nothing difficult.

Post a Comment for "Android Call Method In Service From Activity"