编写简易Android天气应用的代码示例_Android

本文所要介绍的简易天气App主要用RxAndroid、MVP、Retrofit实现,首先来看看效果:
主页内容:

右侧栏天气列表:

左侧栏城市列表

首先看看Activity主要代码(使用MVP模式):

//调用Presenter的方法获取数据
mMainPresenter = new MainPresenterImpl(this);
mMainPresenter.getPlaceData();
mMainPresenter.getWeatherData("成都"); 

//显示主页和右侧栏天气数据
public void setupWeatherData(WeatherResponse weatherResponse) {
  if (weatherResponse == null) return;
  setTitleText(DateUtils.getWeekDay(weatherResponse.date));
  if (weatherResponse.results != null && weatherResponse.results.size() > 0) {
    WeatherResult result = weatherResponse.results.get(0);
    mTvCity.setText(getString(R.string.city, result.currentCity));
    mTvPm25.setText(getString(R.string.pm25, result.pm25)); 

    mWeatherDataAdapter.setData(result.weather_data);
    mWeatherDataAdapter.notifyDataSetChanged(); 

    mWeatherExtraAdapter.setData(result.index);
    mWeatherExtraAdapter.notifyDataSetChanged();
  }
} 

//显示左侧栏城市列表
@Override
public void setupPlaceData(List<Place> placeList) {
  if (placeList == null) {
    return;
  }
  mPlaceAdapter.setData(placeList);
  mPlaceAdapter.notifyDataSetChanged();
} 

接下来看看如何在Presenter中应用RxJava、RxAndroid获取数据

//获取天气数据
@Override
public void getWeatherData(String place) {
  if (TextUtils.isEmpty(place)) {
    return;
  }
  mMainView.showProgress();
  ServiceManager.getInstance().getApiService().getWeatherInfo(place, Constants.BAIDU_AK)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Subscriber<WeatherResponse>() {
        @Override
        public void onCompleted() {
          Log.e(TAG, "onCompleted");
          mMainView.hideProgress();
        } 

        @Override
        public void onError(Throwable e) {
          Log.e(TAG, e.getMessage(), e);
          mMainView.hideProgress();
        } 

        @Override
        public void onNext(WeatherResponse weatherResponse) {
          mMainView.setupWeatherData(weatherResponse);
        }
      });
} 

public interface ApiService { 

  /*@GET("service/getIpInfo.php")
  Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);*/ 

  @GET("service/getIpInfo.php")
  Observable<GetIpInfoResponse> getIpInfo(@Query("ip") String ip); 

  //http://api.map.baidu.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=MPDgj92wUYvRmyaUdQs1XwCf
  @GET("/telematics/v3/weather?output=json")
  Observable<WeatherResponse> getWeatherInfo(@Query("location") String location, @Query("ak") String ak);
} 

如上所述,我们通过百度api获取天气数据使用的是Retrofit框架,它能自动的返回Observable对象。
那么我们如何通过RxJava获取本地文件中的城市列表呢?(为了方便演示,我将城市列表作为一个json字符串放于文件中)

@Override
public void getPlaceData() {
  PlaceRepository repository = new PlaceRepository();
  repository.getPlaceList(BaseApplication.getInstance())
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Subscriber<List<Place>>() {
        @Override
        public void onNext(List<Place> places) {
          mMainView.setupPlaceData(places);
        } 

        @Override
        public void onCompleted() { 

        } 

        @Override
        public void onError(Throwable e) { 

        }
      });
} 

public class PlaceRepository { 

  public Observable<List<Place>> getPlaceList(final Context context) {
    return Observable.create(new Observable.OnSubscribe<List<Place>>() {
      @Override
      public void call(Subscriber<? super List<Place>> subscriber) {
        try {
          AssetManager assertManager = context.getAssets();
          InputStream inputStream = assertManager.open("place");
          ByteArrayOutputStream outStream = new ByteArrayOutputStream();
          byte[] data = new byte[1024];
          int count = -1;
          while((count = inputStream.read(data,0, 1024)) != -1) {
            outStream.write(data, 0, count);
          }
          String json = new String(outStream.toByteArray(),"UTF-8");
          Gson gson = new GsonBuilder().create();
          List<Place> placeList = gson.fromJson(json, new TypeToken<List<Place>>() {}.getType());
          subscriber.onNext(placeList);
        } catch (Exception e) {
          subscriber.onError(e);
        }
        subscriber.onCompleted();
      }
    });
  }
} 

通过上述代码,我们就能完成界面所示功能了,是不是省去了Handler callback,new Thread()这些操作了,这就为什么说RxJava是用来解决Callback Hell的。

 ”在Activity中分别调用了获取天气数据和城市列表的方法,那么问题来了,如果取数据的时候显示了process Dialog, 我该在什么时候结束呢,写flag判断?“

     最直接的最暴力的方法就是直接在一个方法里同步调用两个接口,那使用RxJava怎么实现呢?

     这个问题可以使用RxJava的Merge操作符实现,故名思议就是将两个接口Observable合成一个,废话不说直接上代码:

@Override
public void getPlaceAndWeatherData(String place) {
  mMainView.showProgress();
  PlaceRepository repository = new PlaceRepository();
  Context context = BaseApplication.getInstance();
  Observable placeObservable = repository.getPlaceList(context);
  Observable weatherObservable = ServiceManager.getInstance().getApiService().getWeatherInfo(place, Constants.BAIDU_AK);
  Observable.merge(placeObservable, weatherObservable)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Subscriber<Object>() {
        @Override
        public void onCompleted() {
          mMainView.hideProgress();
        } 

        @Override
        public void onError(Throwable e) {
          mLogger.error(e.getMessage(), e);
          mMainView.hideProgress();
        } 

        @Override
        public void onNext(Object obj) {
          if (obj instanceof List) {
            mMainView.setupPlaceData((List<Place>) obj);
          } else if (obj instanceof WeatherResponse) {
            mMainView.setupWeatherData((WeatherResponse) obj);
          }
        }
      });
} 

这样就很巧妙的解决了如果取数据的时候显示process Dialog、该在什么时候结束、写flag判断的问题。

如果这样的代码看着还不舒服,你完全可以使用Lambda,这样可以让代码看起来少之又少,不过Android studio目前还不支持Lambda,如果想要使用请安装插件RetroLambda 并且JDK 使用JDK 8以上版本.

Github源码地址:https://github.com/mickyliu945/CommonProj

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
天气
android简易天气预报、企业文化 编写示例、心知天气调用示例、心知天气 js调用示例、可交互天气示例,以便于您获取更多的相关知识。

时间: 2024-08-04 04:04:10

编写简易Android天气应用的代码示例_Android的相关文章

编写简易Android天气应用的代码示例

本文所要介绍的简易天气App主要用RxAndroid.MVP.Retrofit实现,首先来看看效果: 主页内容: 右侧栏天气列表: 左侧栏城市列表 首先看看Activity主要代码(使用MVP模式): //调用Presenter的方法获取数据 mMainPresenter = new MainPresenterImpl(this); mMainPresenter.getPlaceData(); mMainPresenter.getWeatherData("成都"); //显示主页和右侧

Android学习笔记--通过Application传递数据代码示例_Android

在整个Android程序中,有时需要保存某些全局的数据(如:用户信息),方便在程序的任何地方调用.在Activity之间数据传递中有一种比较使用的方式,就是全局对象,使用过J2EE的都应该知道JavaWeb的四个作用域,其中Application域在应用程序的任何地方都可以使用和访问,除非是Web服务器停止,Android中的全局对象非常类似于JavaWeb中的Application域,除非是Android应用程序清除内存,否则全局对象将一直可以访问. 在启动Application时,系统会创建

36个Android开发常用经典代码大全_Android

本文汇集36个Android开发常用经典代码片段,包括拨打电话.发送短信.唤醒屏幕并解锁.是否有网络连接.动态显示或者是隐藏软键盘等,希望对您有所帮助. //36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.startActivity( new Intent(Intent.ACTION_CALL, Uri.parse( "tel:" + pho

Android 滑动拦截实例代码解析_Android

废话不多说了,直接给大家贴代码了,具体代码如下所示: package demo.hq.com.fby; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.LinearLayout; /** * Created by huqing on 2016/12/7.

Android开发中编写蓝牙相关功能的核心代码讲解_Android

一. 什么是蓝牙(Bluetooth)?1.1  BuleTooth是目前使用最广泛的无线通信协议 1.2  主要针对短距离设备通讯(10m) 1.3  常用于连接耳机,鼠标和移动通讯设备等.二. 与蓝牙相关的API2.1 BluetoothAdapter: 代表了本地的蓝牙适配器 2.2 BluetoothDevice 代表了一个远程的Bluetooth设备三. 扫描已经配对的蓝牙设备(1)注:必须部署在真实手机上,模拟器无法实现 首先需要在AndroidManifest.xml 声明蓝牙权限

Android中实现基本的短信拦截功能的代码示例_Android

要点 1.在Manifest.xml里加"接收"SMS的权限 <uses-permission Android:name="android.permission.RECEIVE_SMS"></uses-permission> 2.在Manifest.xml里注册一个receive <!-- 注册Receiver,并且设置优先级 --> <receiver android:name=".AutoSMS" a

Android应用开发中使用GridView网格布局的代码示例_Android

基本布局演示1. 定义包含GridView 的 main.xmk <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fil

Android ScrollView使用代码示例_Android

ScrollView可实现控件在超出屏幕范围的情况下滚动显示. 用法:在XML文件中将需滚动的控件包含在ScrollView中,当控件超出屏幕范围时可通过滚动查看:ScrollView也提供了一些方法来控制自身的显示情况.   1.ScrollView中包含其他控件 复制代码 代码如下: <ScrollView          android:id="@+id/scrollView_showMessages"          android:layout_width=&quo

Android应用开发:电话监听和录音代码示例_Android

在oncreate 中执行: 复制代码 代码如下: public void onCreate() {  super.onCreate();  Log.i("TAG", "服务启动了");   // 对电话的来电状态进行监听  TelephonyManager telManager = (TelephonyManager) this    .getSystemService(Context.TELEPHONY_SERVICE);  // 注册一个监听器对电话状态进行监