Java Code Examples for com.lzy.okgo.OkGo

The following examples show how to use com.lzy.okgo.OkGo. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: GoogleVR   Source File: VrVideoFragment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//		super.onViewCreated(view, savedInstanceState);
		recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
		RecyclerView.LayoutManager layoutManager = getLayoutManager();
		recyclerView.setLayoutManager(layoutManager);

		OkGo.get(ApiUrls.URL_Query).cacheKey(ApiUrls.URL_Query).cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {

			@Override
			public void onSuccess(String s, Call call, Response response) {
				try {
					JSONObject obj = new JSONObject(s);
					String content = obj.getString("content");
					List<VideoItem> videoItems = JSON.parseArray(content, VideoItem.class);
					recyclerView.setAdapter(new VrVideoAdapter(videoItems));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
 
Example 2
Source Project: GoogleVR   Source File: ImageDetailActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initPanoView() {
	vrPano = (VrPanoramaView) findViewById(R.id.vr_pano);
	loading = findViewById(R.id.pb_loading);
	Intent intent = getIntent();
	String url = intent.getStringExtra("url");
	String mp3 = intent.getStringExtra("mp3");
	initPlayer(mp3);
	OkGo.get(url).cacheKey(url).execute(new BitmapCallback() {
		@Override
		public void onSuccess(Bitmap bitmap, Call call, Response response) {
			loading.setVisibility(View.GONE);

			VrPanoramaView.Options options = new VrPanoramaView.Options();
			options.inputType = VrPanoramaView.Options.TYPE_MONO;
			vrPano.loadImageFromBitmap(bitmap, options);
		}
	});

}
 
Example 3
Source Project: MyHearts   Source File: HotFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求数据
 */
private void initData() {
    OkGo.post(HttpUrlPaths.THOUGHTS_URL)
            .params("userid",54442)
            .params("labelid",catgId)
            .params("type",1)
            .params("page",page)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(()->{})
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s->{
                Type type = new TypeToken<ThoughtsBean>(){}.getType();
                ThoughtsBean bean = new Gson().fromJson(s,type);
                if (bean.getErrorCode()==0
                        &&bean.getResultCount()>0
                        &&bean.getErrorStr().equals("success")){
                    mThroughtDatas = bean.getResults();
                    mThroughtAdapter.setResultsBeen(mThroughtDatas);
                   /// mRefreshLayout.setClickable(true);
                   // mRefreshLayout.setLoadMore(true);
                }
            },throwable -> {});

}
 
Example 4
Source Project: okhttp-OkGo   Source File: UploadAdapter.java    License: Apache License 2.0 6 votes vote down vote up
public List<UploadTask<?>> updateData(List<ImageItem> images) {
    this.type = -1;
    this.images = images;
    values = new ArrayList<>();
    if (images != null) {
        Random random = new Random();
        for (int i = 0; i < images.size(); i++) {
            ImageItem imageItem = images.get(i);
            //这里是演示可以传递任何数据
            PostRequest<String> postRequest = OkGo.<String>post(Urls.URL_FORM_UPLOAD)//
                    .headers("aaa", "111")//
                    .params("bbb", "222")//
                    .params("fileKey" + i, new File(imageItem.path))//
                    .converter(new StringConvert());

            UploadTask<String> task = OkUpload.request(imageItem.path, postRequest)//
                    .priority(random.nextInt(100))//
                    .extra1(imageItem)//
                    .save();
            values.add(task);
        }
    }
    notifyDataSetChanged();
    return values;
}
 
Example 5
Source Project: MyHearts   Source File: CategoryFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 下拉刷新数据
 *
 * @param url url
 */
private void requestData(String url) {
    limit = lordMoreNum;
    offset = 0;
    if (mIndex == 0) {
        url = HttpUrlPaths.getDouyuLiveChannel(limit, offset);
    } else {
        url = HttpUrlPaths.getDouyuSubChannelBaseTag(mIndex, limit, offset);
    }
    OkGo.get(url)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<RoomInfo>() {
                }.getType();
                RoomInfo roomInfo = new Gson().fromJson(s, type);
                if (roomInfo.getData().size() > 0) {
                    mDataEntities.addAll(roomInfo.getData());
                    mCategoryAdapter.setDataEntities(mDataEntities);
                }
            }, throwable -> {
            });
}
 
Example 6
Source Project: okhttp-OkGo   Source File: DownloadListActivity.java    License: Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.startAll)
public void startAll(View view) {
    for (ApkModel apk : apks) {

        //这里只是演示,表示请求可以传参,怎么传都行,和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(apk.url)//
                .headers("aaa", "111")//
                .params("bbb", "222");

        //这里第一个参数是tag,代表下载任务的唯一标识,传任意字符串都行,需要保证唯一,我这里用url作为了tag
        OkDownload.request(apk.url, request)//
                .priority(apk.priority)//
                .extra1(apk)//
                .save()//
                .register(new LogDownloadListener())//
                .start();
        adapter.notifyDataSetChanged();
    }
}
 
Example 7
Source Project: okhttp-OkGo   Source File: DownloadListActivity.java    License: Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.download)
public void download() {

    //这里只是演示,表示请求可以传参,怎么传都行,和okgo使用方法一样
    GetRequest<File> request = OkGo.<File>get(apk.url)//
            .headers("aaa", "111")//
            .params("bbb", "222");

    //这里第一个参数是tag,代表下载任务的唯一标识,传任意字符串都行,需要保证唯一,我这里用url作为了tag
    OkDownload.request(apk.url, request)//
            .priority(apk.priority)//
            .extra1(apk)//
            .save()//
            .register(new LogDownloadListener())//
            .start();
    adapter.notifyDataSetChanged();
}
 
Example 8
Source Project: okhttp-OkGo   Source File: TestActivity.java    License: Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.btn2)
public void btn2(View view) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Call<JSONObject> adapt = OkGo.<JSONObject>get(Urls.URL_JSONOBJECT).adapt();
                Response<JSONObject> response = adapt.execute();
                System.out.println("body " + response.body());
                Throwable exception = response.getException();
                if (exception != null) exception.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 9
Source Project: MyHearts   Source File: CategoryFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshData(String url) {
    OkGo.get(url)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<RoomInfo>() {
                }.getType();
                RoomInfo roomInfo = new Gson().fromJson(s, type);
                if (roomInfo.getData().size() > 0) {
                    mDataEntities.clear();
                    mDataEntities.addAll(roomInfo.getData());
                    mCategoryAdapter.setDataEntities(mDataEntities);
                }
            }, throwable -> {
            });

}
 
Example 10
Source Project: okhttp-OkGo   Source File: Request.java    License: Apache License 2.0 6 votes vote down vote up
public Request(String url) {
    this.url = url;
    baseUrl = url;
    OkGo go = OkGo.getInstance();
    //默认添加 Accept-Language
    String acceptLanguage = HttpHeaders.getAcceptLanguage();
    if (!TextUtils.isEmpty(acceptLanguage)) headers(HttpHeaders.HEAD_KEY_ACCEPT_LANGUAGE, acceptLanguage);
    //默认添加 User-Agent
    String userAgent = HttpHeaders.getUserAgent();
    if (!TextUtils.isEmpty(userAgent)) headers(HttpHeaders.HEAD_KEY_USER_AGENT, userAgent);
    //添加公共请求参数
    if (go.getCommonParams() != null) params(go.getCommonParams());
    if (go.getCommonHeaders() != null) headers(go.getCommonHeaders());
    //添加缓存模式
    retryCount = go.getRetryCount();
    cacheMode = go.getCacheMode();
    cacheTime = go.getCacheTime();
}
 
Example 11
Source Project: okhttp-OkGo   Source File: Progress.java    License: Apache License 2.0 6 votes vote down vote up
public static Progress changeProgress(final Progress progress, long writeSize, long totalSize, final Action action) {
    progress.totalSize = totalSize;
    progress.currentSize += writeSize;
    progress.tempSize += writeSize;

    long currentTime = SystemClock.elapsedRealtime();
    boolean isNotify = (currentTime - progress.lastRefreshTime) >= OkGo.REFRESH_TIME;
    if (isNotify || progress.currentSize == totalSize) {
        long diffTime = currentTime - progress.lastRefreshTime;
        if (diffTime == 0) diffTime = 1;
        progress.fraction = progress.currentSize * 1.0f / totalSize;
        progress.speed = progress.bufferSpeed(progress.tempSize * 1000 / diffTime);
        progress.lastRefreshTime = currentTime;
        progress.tempSize = 0;
        if (action != null) {
            action.call(progress);
        }
    }
    return progress;
}
 
Example 12
Source Project: MyHearts   Source File: LivingFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求banner图片
 */
private void initBannerData() {
    OkGo.get(HttpUrlPaths.LIVING_STREAMING_BANNER_URL)
            .params("type", "live")
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LivingBannerBean>() {
                }.getType();
                LivingBannerBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorCode() == 0
                        && bean.getErrorStr().equals("success")
                        && bean.getResultCount() > 0) {
                    beanResults = bean.getResults();
                    updateBannerUI(beanResults);
                }
            }, throwable -> {
            });
}
 
Example 13
Source Project: MyHearts   Source File: HomeFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求首页下面展示的图片的第一个banner
 */
private void initRecommentOne() {
    OkGo.post(HttpUrlPaths.HOME_RECOMMENT_ONE_BANNER)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {

            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<HomeBannerOne>() {
                }.getType();
                HomeBannerOne homeBannerOne = new Gson().fromJson(s, type);
                if (homeBannerOne.getErrorStr().equals("success")
                        && homeBannerOne.getErrorCode() == 0) {
                    Glide.with(getContext())
                            .load(homeBannerOne.getResults().getBanner())
                            .asBitmap()
                            .into(mRecommentImgOne);
                }
            }, throwable -> {

            });

}
 
Example 14
Source Project: MyHearts   Source File: HomeFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求推荐咨询师数据
 */
private void initAdvisoryData() {
    OkGo.post(HttpUrlPaths.HOME_RECOMMENT)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {

            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<AdvisoryBean>() {
                }.getType();
                AdvisoryBean bean = new Gson().fromJson(s, type);
                if (bean != null
                        && bean.getErrorCode() == 0
                        && bean.getErrorStr().equals("success")) {
                    mAdvisoryBean = bean.getResults();
                    if (mAdvisoryBean != null && mAdvisoryBean.size() > 0) {
                        initAdvisory(mAdvisoryBean);
                    }
                }
            }, throwable -> {

            });
}
 
Example 15
Source Project: BaseProject   Source File: Request.java    License: Apache License 2.0 6 votes vote down vote up
public Request(String url) {
    this.url = url;
    baseUrl = url;
    OkGo go = OkGo.getInstance();
    //默认添加 Accept-Language
    String acceptLanguage = HttpHeaders.getAcceptLanguage();
    if (!TextUtils.isEmpty(acceptLanguage)) headers(HttpHeaders.HEAD_KEY_ACCEPT_LANGUAGE, acceptLanguage);
    //默认添加 User-Agent
    String userAgent = HttpHeaders.getUserAgent();
    if (!TextUtils.isEmpty(userAgent)) headers(HttpHeaders.HEAD_KEY_USER_AGENT, userAgent);
    //添加公共请求参数
    if (go.getCommonParams() != null) params(go.getCommonParams());
    if (go.getCommonHeaders() != null) headers(go.getCommonHeaders());
    //添加缓存模式
    retryCount = go.getRetryCount();
    cacheMode = go.getCacheMode();
    cacheTime = go.getCacheTime();
}
 
Example 16
Source Project: MyHearts   Source File: OrationActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initData() {
    super.initData();
    OkGo.post(HttpUrlPaths.SCAN_MORE)
            .params("userid", "54442")
            .params("page", page + "")
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {

            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<HomeNewsBean>() {
                }.getType();
                HomeNewsBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorCode() == 0
                        && bean.getErrorStr().equals("success")
                        && bean.getResults().size() > 0) {
                    mOrationDatas = bean.getResults();
                    mOrationAdapter.addData(mOrationDatas);
                }
            }, throwable -> {

            });
}
 
Example 17
Source Project: MyHearts   Source File: LordFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void initLordData() {
    OkGo.post(HttpUrlPaths.LORD_CATEGORY)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {

            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LordBean>() {
                }.getType();
                LordBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorCode() == 0
                        && bean.getErrorStr().equals("success")
                        && bean.getResultCount() > 0) {
                    mLordDatas = bean.getResults();
                    mLordAdapter.setDatas(mLordDatas);
                    mLordAdapter.notifyDataSetChanged();

                }
            }, throwable -> {

            });

}
 
Example 18
Source Project: MyHearts   Source File: LordFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 刷新数据
 */
private void refreshData() {
    OkGo.post(HttpUrlPaths.LORD_CATEGORY)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {

            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LordBean>() {
                }.getType();
                LordBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorCode() == 0
                        && bean.getErrorStr().equals("success")
                        && bean.getResultCount() > 0) {
                    mLordDatas.clear();
                    mLordDatas = bean.getResults();
                    //mLordAdapter.a(mLordDatas);
                    mLordAdapter.setDatas(mLordDatas);
                    mLordRefresh.setRefreshing(false);
                }
            }, throwable -> {

            });
}
 
Example 19
Source Project: MyHearts   Source File: LordDetailActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initRefresh(MaterialRefreshLayout materialRefreshLayout) {
    page = 1; //重置  在刷新的时候
    OkGo.post(HttpUrlPaths.LORD_DETAIL_URL)
            .params("catgId", catgId)
            .params("page", page)
            .params("userid", 0)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LordDetailBean>() {
                }.getType();
                LordDetailBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorStr().equals("success")
                        && bean.getErrorCode() == 0
                        && bean.getResultCount() > 0) {
                    mLordDetailDatas.clear();
                    detailAdapter.notifyDataSetChanged();
                    mLordRefresh.finishRefresh();
                }
            }, throwable -> {
            });


}
 
Example 20
Source Project: MyHearts   Source File: LordDetailActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求数据
 */
private void initLordDetailData() {
    OkGo.post(HttpUrlPaths.LORD_DETAIL_URL)
            .params("catgId", catgId)
            .params("page", page)
            .params("userid", 0)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LordDetailBean>() {
                }.getType();
                LordDetailBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorStr().equals("success")
                        && bean.getErrorCode() == 0
                        && bean.getResultCount() > 0) {
                    mLordDetailDatas = bean.getResults();
                    detailAdapter.addData(mLordDetailDatas);
                }
            }, throwable -> {
            });

}
 
Example 21
Source Project: DevUtils   Source File: OkGoDemo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取用户列表
 * @param okCallback
 */
public static void getUserList(OkGoCallback<List<UserBean>> okCallback) {
    OkGo.<String>post("url").tag(OkGoDemo.class)
            .execute(okCallback);
    // 取消请求
    // OkGo.getInstance().cancelTag(OKDemo.class);
    // 请求管理控制 ( 取消请求 ) 查看 OkGoUtils#execute 方法
}
 
Example 22
@Override
protected void onDestroy() {
    super.onDestroy();
    // 关闭堆栈中的Activity
    AppManager.getAppManager().finishActivity(activity);
    //在onDestroy()生命周期中释放P中引用的V。
    presenter.detach();
    //在onDestroy()生命周期中取消所有子线程里面的网络连接。

    OkGo.getInstance().cancelTag(activity);
    if (mImmersionBar != null) {
        mImmersionBar.destroy();  //在BaseActivity里销毁
    }

}
 
Example 23
@Override
public void onDestroy() {
    super.onDestroy();
    //在onDestroy()生命周期中释放P中引用的V。
    presenter.detach();
    //在onDestroy()生命周期中取消所有子线程里面的网络连接。
    OkGo.getInstance().cancelTag(getActivity());
    if (mImmersionBar != null) {
        mImmersionBar.destroy();
    }
}
 
Example 24
Source Project: GoogleVR   Source File: MyApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	//全局初始化
	OkGo.init(this);
	OkGo.getInstance().setConnectTimeout(3000)
			.setReadTimeOut(3000)
			.setWriteTimeOut(3000)
			.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
			.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
			.setRetryCount(3);
}
 
Example 25
Source Project: KUtils-master   Source File: KUtilLibs.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化库
 *
 * @param isDebug 是否打印日志
 * @param TAG     日志TAG
 * @param context application
 */
public static void init(@NonNull boolean isDebug, @NonNull String TAG, @NonNull Application context) {
    android.util.Log.d(TAG_, "==============您使用的KUtils版本:2.4.2==============");
    if (TAG == null || context == null) throw new RuntimeException("KUtilLibs 初始化参数均不能为空");
    appContext = context.getApplicationContext();
    if (isDebug) Log.init(TAG, true);//开启日志打印
    DialogUIUtils.init(appContext);
    OkGo.getInstance().init(context);
}
 
Example 26
Source Project: okhttp-OkGo   Source File: ServerApi.java    License: Apache License 2.0 5 votes vote down vote up
public static Observable<Response<Bitmap>> getBitmap(String header, String param) {
    return OkGo.<Bitmap>post(Urls.URL_IMAGE)//
            .headers("aaa", header)//
            .params("bbb", param)//
            .converter(new BitmapConvert())//
            .adapt(new ObservableResponse<Bitmap>());
}
 
Example 27
Source Project: okhttp-OkGo   Source File: RxCommonActivity.java    License: Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.commonRequest)
public void commonRequest(View view) {
    OkGo.<String>post(Urls.URL_METHOD)//
            .headers("aaa", "111")//
            .params("bbb", "222")//
            .converter(new StringConvert())//
            .adapt(new ObservableResponse<String>())//
            .subscribeOn(Schedulers.io())//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    showLoading();
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Response<String>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Response<String> response) {
                    handleResponse(response);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    showToast("请求失败");
                    handleError(null);
                }

                @Override
                public void onComplete() {
                    dismissLoading();
                }
            });
}
 
Example 28
Source Project: okhttp-OkGo   Source File: RxCommonActivity.java    License: Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.upString)
public void upString(View view) {
    OkGo.<String>post(Urls.URL_TEXT_UPLOAD)//
            .headers("aaa", "111")//
            .upString("上传的文本。。。")//
            .converter(new StringConvert())//
            .adapt(new ObservableResponse<String>())//
            .subscribeOn(Schedulers.io())//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    showLoading();
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Response<String>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Response<String> response) {
                    handleResponse(response);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    showToast("请求失败");
                    handleError(null);
                }

                @Override
                public void onComplete() {
                    dismissLoading();
                }
            });
}
 
Example 29
Source Project: okhttp-OkGo   Source File: DesActivity.java    License: Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.start)
public void start() {
    if (task == null) {

        //这里只是演示,表示请求可以传参,怎么传都行,和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(apk.url)//
                .headers("aaa", "111")//
                .params("bbb", "222");

        task = OkDownload.request(apk.url, request)//
                .priority(apk.priority)//
                .extra1(apk)//
                .save()//
                .register(new DesListener("DesListener"))//
                .register(new LogDownloadListener());
    }
    switch (task.progress.status) {
        case Progress.PAUSE:
        case Progress.NONE:
        case Progress.ERROR:
            task.start();
            break;
        case Progress.LOADING:
            task.pause();
            break;
        case Progress.FINISH:
            File file = new File(task.progress.filePath);
            if (ApkUtils.isAvailable(this, file)) {
                ApkUtils.uninstall(this, ApkUtils.getPackageName(this, file.getAbsolutePath()));
            } else {
                ApkUtils.install(this, file);
            }
            break;
    }
}
 
Example 30
Source Project: MyHearts   Source File: LivingFragment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 进入就刷新
 */
private void delayInitData() {
    //mRefreshLayout.setRefreshing(true);  //自动刷新

    OkGo.get(HttpUrlPaths.LIVING_STREAMING_URL)
            .params("userid", "54442")
            .params("page", page)
            .getCall(StringConvert.create(), RxAdapter.<String>create())
            .doOnSubscribe(() -> {
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s -> {
                Type type = new TypeToken<LivingBean>() {
                }.getType();
                LivingBean bean = new Gson().fromJson(s, type);
                if (bean.getErrorCode() == 0
                        && bean.getResultCount() > 0
                        && bean.getErrorStr().equals("success")) {
                    List<LivingBean.ResultsEntity> results = bean.getResults();
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mResultsEntities = results;
                    mLivingAdapter.setEntities(mResultsEntities);
                    mRefreshLayout.setRefreshing(false);
                }
            }, throwable -> {
            });
}