Set google as search bar in home screen Custom launcher programmatically Set google as search bar in home screen Custom launcher programmatically android android

Set google as search bar in home screen Custom launcher programmatically


I really recommend you to clone Launcher3 repository from AOSP.

https://android.googlesource.com/platform/packages/apps/Launcher3/

If you checkout nougat-mr5 branch you can look at the code to show searchbar by taking the component from GMS package and including it as a row element. Please look for QSB in the code.


The search bar is not displayed because the launcher doesn't have permissions to show the widget.

As you probably already figured out, if a user explicitly adds the search bar widget to any screen, he will be prompted to give the permission, and the search bar on top also appears.

The problem is that getOrCreateQsbBar method in Launcher class (I assume you forked Launcher3) doesn't ask for permissions if it can't instantiate the widget, it instead silently fails. The problem is in this snippet inside of getOrCreateQsbBar:

    if (!AppWidgetManagerCompat.getInstance(this)            .bindAppWidgetIdIfAllowed(widgetId, searchProvider, opts)) {        mAppWidgetHost.deleteAppWidgetId(widgetId);        widgetId = -1;    }

Instead of just resetting widgetId to -1 you want to ask for permissions to install the widget and call getOrCreateQsbBar again. Here's an example code that asks for permission:

    boolean hasPermission = appWidgetManager.bindAppWidgetIdIfAllowed(widgetId, searchProvider);    if (!hasPermission)    {        mAppWidgetHost.deleteAppWidgetId(widgetId);        widgetId = -1;        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, searchProvider);        startActivityForResult(intent, REQUEST_BIND);    }

Then overload onActivityResult in the Launcher class, something along the lines of:

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data);    if (requestCode == REQUEST_BIND) {        mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());    } }