Set google as search bar in home screen Custom launcher programmatically

1.4k views Asked by At

I am creating 'my own launcher. In that case I want to putQuick search bar` in my home screen i.e. Google now launcher.

How can I do that. I have gone through multiple threads but not found any relevant answer.

I don't want to show the widget picker.I want asap user install this launcher search bar should be there.

Thanks in advance.

2

There are 2 answers

0
Ishamael On BEST ANSWER

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:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_BIND) {
        mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
    } 
}
0
Santiago Martínez On

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.