博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
苹果x翻新机序列号开头_Android翻新电话每隔X秒
阅读量:2535 次
发布时间:2019-05-11

本文共 7685 字,大约阅读时间需要 25 分钟。

苹果x翻新机序列号开头

In this tutorial, we’ll be implementing RxJava with Retrofit such that the Retrofit Service is called every x seconds in our Android Application.

在本教程中,我们将使用Retrofit实现RxJava,以便在Android应用程序中每x秒调用一次Retrofit服务。

Android RxJava和改造 (Android RxJava and Retrofit)

We have already discussed the basics of RxJava and Retrofit together, .

我们已经在一起讨论了RxJava和Retrofit的基础。

In order to create a Retrofit service that runs after certain time intervals, we can use the following :

为了创建在特定时间间隔后运行的Retrofit服务,我们可以使用以下命令:

  • Handlers

    处理程序
  • RxJava

    RxJava的

Handlers are used to communicate/pass data from the background thread to the UI thread

处理程序用于将数据从后台线程传递/传递到UI线程

Using RxJava we can do much more than that and very easily as well, using RxJava operators.

We can use the interval operator to call a certain method ( retrofit network call in our case) after every given period.

使用RxJava,我们可以使用RxJava运算符做更多的事情,而且非常容易。

在每个给定时间段之后,我们可以使用间隔运算符来调用某种方法(在我们的情况下为翻新网络调用)。

Observable.interval operator is used to emit values after certain intervals. It looks like this:

Observable.interval运算符用于在特定间隔后发出值。 看起来像这样:

Observable.interval(1000, 5000,                    TimeUnit.MILLISECONDS);

1000 is the initial delay before the emission starts and repeats every 5 seconds.

1000是发射开始之前的初始延迟,每5秒重复一次。

We can subscribe our observers which would call the Retrofit method after every 5 seconds.

我们可以订阅观察者,该观察者每5秒就会调用Retrofit方法。

Calling Retrofit service after certain intervals is fairly common in applications that provide live updates, such as Cricket Score application etc.

在某些时间间隔后调用翻新服务在提供实时更新的应用程序中非常普遍,例如板球得分应用程序等。

Let’s get started with our implementation in the following section. We’ll be creating an application which shows a new random joke in the TextView after every 5 seconds.

在下一节中,让我们开始实施。 我们将创建一个应用程序,该应用程序每隔5秒就会在TextView中显示一个新的随机笑话。

项目结构 (Project Structure)

Add the following dependencies to the build.gradle file:

将以下依赖项添加到build.gradle文件:

implementation('com.squareup.retrofit2:retrofit:2.3.0')            {                exclude module: 'okhttp'            }    implementation 'io.reactivex.rxjava2:rxjava:2.1.9'    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

In order to use lambda syntax, make sure that the compile options are set as the following inside the android block in the build.gradle.

为了使用lambda语法,请确保在build.gradle的android块内将编译选项设置为以下内容。

android{...compileOptions {        targetCompatibility 1.8        sourceCompatibility 1.8    }...}

(Code)

The code for the activity_main.xml layout is given below:

下面给出了activity_main.xml布局的代码:

We’ll be using the following public API:

.

我们将使用以下公共API:

Create an APIService.java class where the API is defined:

创建定义了API的APIService.java类:

package com.journaldev.androidretrofitcalleveryxsecond;import io.reactivex.Observable;import retrofit2.http.GET;import retrofit2.http.Path;public interface APIService {    String BASE_URL = "https://api.chucknorris.io/jokes/";    @GET("{path}")    Observable
getRandomJoke(@Path("path") String path);}

Following is the POJO model for the Jokes.java class :

以下是Jokes.java类的POJO模型:

package com.journaldev.androidretrofitcalleveryxsecond;import com.google.gson.annotations.SerializedName;import java.util.List;public class Jokes {    @SerializedName("url")    public String url;    @SerializedName("icon_url")    public String icon_url;    @SerializedName("value")    public String value;}

The code for the MainActivity.java is given below:

MainActivity.java的代码如下:

package com.journaldev.androidretrofitcalleveryxsecond;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.widget.TextView;import android.widget.Toast;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import java.util.concurrent.TimeUnit;import io.reactivex.Observable;import io.reactivex.android.schedulers.AndroidSchedulers;import io.reactivex.disposables.Disposable;import io.reactivex.schedulers.Schedulers;import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Retrofit;import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;import retrofit2.converter.gson.GsonConverterFactory;import static com.journaldev.androidretrofitcalleveryxsecond.APIService.BASE_URL;public class MainActivity extends AppCompatActivity {    Retrofit retrofit;    TextView textView;    APIService apiService;    Disposable disposable;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = findViewById(R.id.textView);        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(interceptor)                .connectTimeout(30, TimeUnit.SECONDS)                .readTimeout(30, TimeUnit.SECONDS)                .writeTimeout(30, TimeUnit.SECONDS)                .build();        Gson gson = new GsonBuilder()                .setLenient()                .create();        retrofit = new Retrofit.Builder()                .baseUrl(BASE_URL)                .client(client)                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                .addConverterFactory(GsonConverterFactory.create(gson))                .build();        apiService = retrofit.create(APIService.class);        disposable = Observable.interval(1000, 5000,                TimeUnit.MILLISECONDS)                .observeOn(AndroidSchedulers.mainThread())                .subscribe(this::callJokesEndpoint, this::onError);    }    @Override    protected void onResume() {        super.onResume();        if (disposable.isDisposed()) {            disposable = Observable.interval(1000, 5000,                    TimeUnit.MILLISECONDS)                    .observeOn(AndroidSchedulers.mainThread())                    .subscribe(this::callJokesEndpoint, this::onError);        }    }    private void callJokesEndpoint(Long aLong) {        Observable
observable = apiService.getRandomJoke("random"); observable.subscribeOn(Schedulers.newThread()). observeOn(AndroidSchedulers.mainThread()) .map(result -> result.value) .subscribe(this::handleResults, this::handleError); } private void onError(Throwable throwable) { Toast.makeText(this, "OnError in Observable Timer", Toast.LENGTH_LONG).show(); } private void handleResults(String joke) { if (!TextUtils.isEmpty(joke)) { textView.setText(joke); } else { Toast.makeText(this, "NO RESULTS FOUND", Toast.LENGTH_LONG).show(); } } private void handleError(Throwable t) { //Add your error here. } @Override protected void onPause() { super.onPause(); disposable.dispose(); }}

setLenient() is used to prevent Misinformed JSON response exceptions.

setLenient()用于防止错误的JSON响应异常。

The disposable instance is unsubscribed when the user leaves the activity.

当用户离开活动时,该一次性实例将取消订阅。

Check the isDisposed method on the Disposable before creating the Observable stream again in the onResume method.

onResume方法中再次创建Observable流之前,请检查Disposable上的isDisposed方法。

The output of the application in action is given below:

实际应用程序的输出如下:

That brings an end to this tutorial. You can download the project from the link below:

这样就结束了本教程。 您可以从下面的链接下载项目:

翻译自:

苹果x翻新机序列号开头

转载地址:http://wqmzd.baihongyu.com/

你可能感兴趣的文章
JPA框架学习
查看>>
JPA、JTA、XA相关索引
查看>>
机器分配
查看>>
php opcode缓存
查看>>
springcloud之Feign、ribbon设置超时时间和重试机制的总结
查看>>
Go 结构体
查看>>
LINQ巩固
查看>>
观看杨老师(杨旭)Asp.Net Core MVC入门教程记录
查看>>
UIDynamic(物理仿真)
查看>>
Windows下安装Redis
查看>>
迷宫实现
查看>>
【字符编码】Java字符编码详细解答及问题探讨
查看>>
学习操作系统导图
查看>>
在线的JSON formate工具
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
xml解析
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
hdu--1698 Just a Hook(线段树+区间更新+懒惰标记)
查看>>
Python学习笔记-EXCEL操作
查看>>