[英]How to show spinning progress dialogue with using separate Async Task Class
[英]How to show spinning icon while using retrofit 2 to get a response from Async Restful call
我使用 Square / Retrofit Restful 框架從 Restful 服務中獲取數據,它的工作原理非常棒,代碼片段如下所示:
FooService restInterface = new RestAdapter.Builder().setEndpoint(FooService.URL).build().create(FooService.class);
restInterface.getAllFoos(new Callback<FooModel>() {
@Override
public void success(FooModel model, Response response) {
//get a list of Foo instances.
}
updateUI();
}
@Override
public void failure(RetrofitError error) {
//log errors.
}
});
我知道這是一個異步調用,但是當 retrofit 忙於在后台工作時,我可以在頂部有一個旋轉圖標嗎? 如果.network 不可用。
還可以設置超時,以便在時間到時提示繼續等待或中止任務的選項嗎?
我注意到這個網站上有一些接近的東西: Is it possible to show progress bar when upload image via Retrofit 2 ,但仍然無法弄清楚如何去做。 此外,我的要求可能更簡單。
更好的方法是將這段邏輯整合到一個中心位置。 為此,您可以使用攔截器並根據您的應用發出的任何請求廣播本地意圖。
看一下 Kotlin 中編寫的攔截器 class(在 Java 上同樣有效):
internal class BusyInterceptor constructor(val appContext: Context) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
// Times are different, so it does handle request and response at the same time
Log.d("REQUEST BUSY INTERCEPTOR------------>","request time: " + t1)
val intent = Intent()
intent.action = "IS_BUSY"
intent.putExtra("isBusy", true)
LocalBroadcastManager.getInstance(appContext).sendBroadcast(intent)
val response: Response = chain.proceed(request)
val t2 = System.nanoTime()
Log.d("RESPONSE BUSY INTERCEPTOR------------>","request time: " + t2)
val intent2 = Intent()
intent2.action = "IS_BUSY"
intent2.putExtra("isBusy", false)
LocalBroadcastManager.getInstance(appContext).sendBroadcast(intent2)
return response
}
}
然后你只需將攔截器添加到你的 okhttp 客戶端:
// Add Busy Interceptor
val busyInterceptor = BusyInterceptor(appContext)
okHttpClient.addInterceptor(busyInterceptor)
這樣,您就不再依賴於任何特定的活動/片段,您只需確保您使用的是應用程序文件,並注冊廣播。
即 MyApplication.java:
@Override
public void onCreate() {
super.onCreate();
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getBooleanExtra("isBusy", false)){
ProgressHUD.showDummyProcessing(getCurrentActivity());
} else {
ProgressHUD.hideDummyProcessing(getCurrentActivity());
}
}
};
IntentFilter filter = new IntentFilter("IS_BUSY");
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
這使您可以靈活地決定每次發出請求時要做什么,而不管用戶當前在哪里。
為簡單起見,我沒有包含隊列邏輯來管理多個/並行請求,但是使用 ArrayList 或類似的方法在同一個文件中跟蹤它相當簡單。
此外,有些 this 支持“靜默”請求,您不想向用戶顯示任何反饋(分析、日志記錄等),只需在意圖中傳遞額外的“額外”:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.