javaandroidandroid-autoandroid-mediasessionmediabrowserservicecompat

How to show search results in Android Car using UI keybord: sendResult() called when either sendResult() or sendError() had already been called for


I have an android media browser service app and want to make it ready for Android Car. I want to implement keyboard search. For that I implement onSearch() method.

ExecuteSearch(query) does the search and returns a MediaItemList.

    @Override
    public void onSearch(@NonNull String query, Bundle extras, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
    super.onSearch(query, extras, result);

    result.detach();
    executeSearch(query)
            .addOnSuccessListener(mediaItems -> {
                result.sendResult(mediaItems);
            })
            .addOnFailureListener(e -> {
                result.sendResult(null);
            });
}

This method is executed after every input on the keyboard. After entering the first character I get the error message (b ist the character I'm searching for using the car UI keyboard)

java.lang.IllegalStateException: sendResult() called when either sendResult() or sendError() had already been called for: b

Does anyone know how to show search results in Android Car?

Thank you! GGK


Solution

  • I think the issue you're running into is calling super.onSearch(query, extras, result). The default implementation of onSearch in MediaBrowserServiceCompat calls sendResult(null).

    So your code is effectively the same as:

    public void onSearch(@NonNull String query, Bundle extras, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
        result.sendResult(null);
    
        executeSearch(query)
                .addOnSuccessListener(mediaItems -> {
                    result.sendResult(mediaItems);
                })
                .addOnFailureListener(e -> {
                    result.sendResult(null);
                });
    }
    

    Meaning that, when you call sendResult on success, it's the second time it's been called.