1

这几天我一直在为这个问题苦苦挣扎。所以我想在 Android Slices 上做的是使用来自后端服务的信息创建切片。例如:在 SliceProvider 类上

@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
    }
}

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

4

1 回答 1

0

根据此处的谷歌文档:

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)方法中使用产品数据

于 2019-01-31T16:43:49.193 回答