Send message from Activity to Service - Android

2019-01-29 02:38发布

问题:

I am writing a keyboard replacement app for Android, and I needed the keyboard customized enough that I need to run it in an Activity, instead of keeping it in the InputMethodService class. Here is how I call the keyboard from my InputMethodService class:

    @Override public void onStartInputView(EditorInfo attribute, boolean restarting) {
    super.onStartInputView(attribute, restarting);

    Intent intent = new Intent(this, Keyboard.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    context.startActivity(intent);

}

I have now run into the problem that I can't update the text field where the input from the keyboard should go. I tried creating a static InputConnection, in my service class, then updating it from the Activity, but nothing happens.

So I guess here is my question: I was able to find lots of info about how to send data from a Service to an Activity, but nothing about sending data from an Activity to a Service(specifically an input method service). Does anyone know how to do this?

回答1:

Use a Binder for that.

This tutorial about music player service is a good sample http://www.helloandroid.com/tutorials/musicdroid-audio-player-part-ii

Especially this line

mpInterface.addSongPlaylist(file.getName());