views:

203

answers:

2

I have the folowing method in a Service in my appplication:

public void switchSpeaker(boolean speakerFlag){

        if(speakerFlag){
        audio_service.setSpeakerphoneOn(false);
        }
        else{
        audio_service.setSpeakerphoneOn(true);
        }

    }

So my question is whats the best and most effective way to be able to use this method in an Activity like follows

final Button speaker_Button = (Button) findViewById(R.id.widget36);

            speaker_Button.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v){

                    switchSpeaker(true); //method from Service

                }

            });

Do I have to do an AIDL or is there a simpler way?

+2  A: 

Hello,

You have to expose service`s switchSpeaker method for clients. Define your .aidl file. Than bind to that service from your activity and simply call switchSpeaker. See documentation

No other simple way to call this method, only if it static)

ponkin
+1  A: 

It's public, right :)

You can call bindService(Intent) method. Tale a look at ApiDemos, the class LocalServiceBinding.

In the callback method onServiceConnected, you can see:

    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service.  Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        mBoundService = ((LocalService.LocalBinder)service).getService();

        // Tell the user about this for our demo.
        Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
                Toast.LENGTH_SHORT).show();
    }

Now, use the service object (mBoundService) to call the method.

That's all :)

Bino