Set google as search bar in home screen Custom launcher programmatically

你离开我真会死。 提交于 2019-12-10 12:33:52

问题


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.


回答1:


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());
    } 
}



回答2:


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.



来源:https://stackoverflow.com/questions/42339932/set-google-as-search-bar-in-home-screen-custom-launcher-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!