如何在切片提供商上进行网络 API 调用,并在切片上设置信息



几天我一直在这个问题上挣扎。因此,我想在Android Slices上做的是使用来自后端服务的信息创建切片。例如:在切片提供程序类上

@Override
public Slice onBindSlice(Uri sliceUri) {
    l.d(TAG,"onBindSlice called");
    switch (sliceUri.getPath()) {
        case "/product":
            makeRequestForProduct();
            return createProductSlice(sliceUri);
    }
    return null;
}

private void makeRequestForProduct() {
    String url = Environment.getInstance().getCompleteUrl("etc..");
    RetrofitFactory.defaultBuilder(ProductWebInterface.class)
            .getProductResponse(url).enqueue(new ProductWebcallback());
}
public void onEventMainThread(ProductReceivedEvent response) {
    if (response.getProduct() != null) { //do something
    }
}

但我不知道该怎么做。上面的代码不起作用。它给了我一个例外。

根据谷歌文档在这里:

onBindSlice should return as quickly as possible so that the UI tied to this slice can be responsive. No network or other IO will be allowed during onBindSlice. Any loading that needs to be done should happen in the background with a call to ContentResolver.notifyChange(Uri, ContentObserver) when the app is ready to provide the complete data in onBindSlice.

因此,您必须在后台线程中完成工作。

请参阅下面的 Kotlin 示例:

 private fun makeRequestForProductInTheBackground(sliceUri : SliceUri) {
        Completable.fromAction {
            makeRequestForProduct(sliceUri)
        }.subscribeOn(Schedulers.io()).subscribe()
 }

请求完成后,您可以将数据保存在某个地方,例如变量或存储库。

fun onEventMainThread(response: ProductReceivedEvent) {
        if (response.getProduct() != null) { 
          //Save your data in a variable or something depending on your needs
          product == response.getProduct()
          //This will call the *onBindSlice()* method again
          context?.contentResolver?.notifyChange(sliceUri, null)
        }
    }

然后,您可以在 createProductSlice(sliceUri) 方法中使用产品数据

最新更新