几天来我一直在努力解决这个问题。因此,我想在Android Slices上执行的操作是使用来自后端服务的信息创建slice。例如:
在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
    }
}


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

最佳答案

根据Google文档here

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

关于android - 如何在SliceProvider上进行网络API调用并在Slice上设置信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54187112/

10-09 16:01