相关搜索

请求搜索建议界面视图生成器

如需获取搜索建议界面视图,您应先按照以下步骤获取其生成器:

  1. 让目标 Activity 类实现 GetSearchSuggestionsViewGeneratorCallback 接口或使用匿名内部类。
  2. 替换 GetSearchSuggestionsViewGeneratorCallback 接口的 onSuccess(SearchSuggestionsViewGenerator)onError(String) 方法。
  3. 使用搜索上下文列表构建 GetSearchSuggestionsViewOptions 类实例。(可选)此对象还接受 SearchSuggestionsViewOptions 对象,该对象提供了一些用于自定义搜索建议界面外观的选项。
  4. 调用 SearchInAppsServicegetSearchSuggestionsView(GetSearchSuggestionsViewOptions, GetSearchSuggestionsViewGeneratorCallback) 函数。
  5. 获取界面生成器后,您可以考虑将其存储在 ViewModel 中,以便在需要重新创建 activity 时(例如在应用运行期间配置发生更改时)无需再次请求生成器。

示例代码

Java

package ...;

...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
import java.util.Arrays;
import java.util.List;
...

public class MainActivity extends AppCompatActivity implements GetSearchSuggestionsViewGeneratorCallback {
  private SearchInAppsService service;

  @Override
  public void onSuccess(SearchSuggestionsViewGenerator generator) {
    ...
  }

  @Override
  public void onError(String errorMessage) {
    ...
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...
    service = SearchInAppsService.create(this);
    // Right now only the first element of this list will be used.
  List<String> searchContext = Arrays.asList(new String[]{"This is a test query, for example."});
    // Uses the default SearchSuggestionsViewOptions.
    service.getSearchSuggestionsView(
      new GetSearchSuggestionsViewOptions().setTextContext(searchContext),this);
    ...
  }

  @Override
  public void onDestroy() {
    service.shutDown();
    super.onDestroy();
  }
}

Jetpack Compose

package ...

...
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      SearchSuggestionsUI()
    }
  }

  @Composable
  fun SearchSuggestionsUI() {
    ...
    var service by remember {
      mutableStateOf<SearchInAppsService?>(
        SearchInAppsService.create(LocalContext.current))
    }
    DisposableEffect(Unit) { onDispose { service?.shutDown() } }
    val callback =
              object : GetSearchSuggestionsViewGeneratorCallback {
                override fun onSuccess(generator: SearchSuggestionsViewGenerator) {
                  ...
                }

              override fun onError(errorMessage: String) {
                ...
              }
            }
  var searchContexts: List<String> = listOf<String>("Query")
  // Uses the default SearchSuggestionsViewOptions.
  var options: GetSearchSuggestionsViewOptions =
            GetSearchSuggestionsViewOptions()
              .setTextContext(searchContexts)
  service?.getSearchSuggestionsView(options, callback)
  ...
 }
}

请求基于位置的搜索建议

getSearchSuggestionsView 入口点还支持基于位置的搜索建议。按照以下步骤构建包含 LocationContext 对象列表的 GetSearchSuggestionsViewOptions 对象。然后,按照上一部分中的步骤将 GetSearchSuggestionsViewOptions 传递给 getSearchSuggestionsView 函数。

  1. (必需)使用 GeographicalRestrictions 对象构建 LocationContext 对象。GeographicalRestrictions 对象接受一个 CircularArea 对象,其中包含区域中心的纬度和经度以及区域的半径。
  2. (可选)使用 TimeSegment 对象构建 TimeRestrictions 对象。TimeSegment 对象接受一个字符串,该字符串采用 ISO 8601 格式表示时间段。
  3. (可选)使用请求的地理位置类型构建 GeoTypeRestrictions 对象。提供的类型用于调整服务返回的结果的排名和过滤。支持的值包括:"restaurant"、"cafe"、"bar"、"park"、"zoo"、"museum"、"attraction"、"atm"、"bank"、"hair_salon"、"real_estate_agency"、"bicycle_sharing_location"、"car_rental_agency"、"shopping_center"、"grocery_store" 和 "hotel"。

示例代码

Java

package ...;

...
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.LocationContext;
import com.google.android.libraries.searchinapps.LocationContext.CircularArea;
import com.google.android.libraries.searchinapps.LocationContext.GeoTypeRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.GeographicalRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.LatLng;
import com.google.android.libraries.searchinapps.LocationContext.TimeRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.TimeSegment;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
...
LocationContext locationContext = new LocationContext(
    new GeographicalRestrictions(
        new CircularArea(
            new LatLng(
                40.7414728,
                -74.0059622),
                1000)))
    // Optional. If set, the returned suggestions are categories of which
    // there are several businesses in the requested area that are open at
    // the given time.
    .setTimeRestrictions(
      new TimeRestrictions(
        new TimeSegment("2024-05-18T19:20:30.45+01:00")))
    // Optional. If set, the returned suggestions are subset of the
    // requested categories.
    .setGeoTypeRestrictions(
      new GeoTypeRestrictions("restaurant", "parks"));

// Uses the default SearchSuggestionsViewOptions.
service = SearchInAppsService.create(this);
// Uses the default SearchSuggestionsViewOptions.
service.getSearchSuggestionsView(
  new GetSearchSuggestionsViewOptions().setLocationContext(Arrays.asList(locationContext)), this);

Jetpack Compose

package ...

...
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.LocationContext
import com.google.android.libraries.searchinapps.LocationContext.CircularArea
import com.google.android.libraries.searchinapps.LocationContext.GeoTypeRestrictions
import com.google.android.libraries.searchinapps.LocationContext.GeographicalRestrictions
import com.google.android.libraries.searchinapps.LocationContext.LatLng
import com.google.android.libraries.searchinapps.LocationContext.TimeRestrictions
import com.google.android.libraries.searchinapps.LocationContext.TimeSegment
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...

var locationContext: LocationContext = LocationContext(
  GeographicalRestrictions(
    CircularArea(
      LatLng(40.7414728, -74.0059622),
      1000)))
  // Optional. If set, there are several businesses in the requested area that
  // are open at the given time.
  .setTimeRestrictions(
    TimeRestrictions(
      TimeSegment("2024-05-18T19:20:30.45+01:00")))
  // Optional. If set, the returned suggestions are subset of the requested
  // categories.
  .setGeoTypeRestrictions(
    GeoTypeRestrictions("restaurant", "parks"))

// Uses the default SearchSuggestionsViewOptions.
var options: GetSearchSuggestionsViewOptions =
          GetSearchSuggestionsViewOptions()
            .setLocationContext(listOf<LocationContext>(locationContext))
service.getSearchSuggestionsView(options, callback)
...

添加搜索建议界面视图

对于 getSearchSuggestionsView,最终输出为 SearchSuggestionsViewGenerator 对象。您可以使用此对象的 populateView(Context) 函数生成界面视图,并使用 updateView(View) 更新现有视图(对于 Jetpack Compose 应用尤其如此)。

对于 Jetpack Compose 应用,您应使用 AndroidView 来使用生成的传统视图。

示例代码

Java

package ...;

...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
import java.util.Arrays;
import java.util.List;
...

public class MainActivity extends AppCompatActivity implements GetSearchSuggestionsViewGeneratorCallback {
  private SearchInAppsService service;

  @Override
  public void onSuccess(SearchSuggestionsViewGenerator generator) {
    ViewGroup container = findViewById(R.id.[container_id]);
    container.removeAllViews();
    container.addView(generator.populateView(this));
  }

  @Override
  public void onError(String errorMessage) {
    ...
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...
    service = SearchInAppsService.create(this);
    List<String> searchContext = Arrays.asList(new String[]{"Query"});
    // Uses the default SearchSuggestionsViewOptions.
    service.getSearchSuggestionsView(
      new GetSearchSuggestionsViewOptions().setTextContext(searchContext),this);
    ...
  }

  @Override
  public void onDestroy() {
    service.shutDown();
    super.onDestroy();
  }
}

Jetpack Compose

package ...

...
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent { SearchSuggestionsUI() }
  }

  @Composable
  fun SearchSuggestionsUI() {
    ...
    var service by remember {
      mutableStateOf<SearchInAppsService?>(
        SearchInAppsService.create(LocalContext.current))
    }
    var viewGenerator = mutableStateOf<SearchSuggestionsViewGenerator?>(null)
    DisposableEffect(Unit) { onDispose { service?.shutDown() } }
    val callback =
      object : GetSearchSuggestionsViewGeneratorCallback {
        override fun onSuccess(generator: SearchSuggestionsViewGenerator) {
          viewGenerator.value = generator
        }

      override fun onError(errorMessage: String) {}
    }
  var searchContexts: List<String> = listOf<String>("Query")
  // Uses the default SearchSuggestionsViewOptions.
  var options: GetSearchSuggestionsViewOptions =
    GetSearchSuggestionsViewOptions().setTextContext(searchContexts)
  service?.getSearchSuggestionsView(options, callback)
  ChipGroupUI(viewGenerator)
  ...
}

  @Composable
  fun ChipGroupUI(viewGenerator: MutableState<SearchSuggestionsViewGenerator?>) {
    viewGenerator.value?.let { viewGenerator ->
      var context = LocalContext.current
      AndroidView(
        factory = { context -> viewGenerator.populateView(context) },
        update = { view -> viewGenerator.updateView(view, context) },
      )
    }
  }
}

下一步:显示搜索结果