Android开发欧酷天气

今天写完了郭神的第二行代码的欧酷天气
用到了litepal、okhttp3等技术使得代码变得通俗易懂
与之前自己参考的项目项目,让我觉得最大的变化就是数据库操作变得十分之简单
学到了很多关于这方面的知识
本项目的重要的几个点:
1、关于数据库使用litepal
2、xml界面关于framelayout、fragment、refersh的使用
3、关于使用okhttp来进行网络申请
4、处理网页返回的数据使用JSON解析
5、关于后台更新 service的构造

1、数据库使用litepal:
有几个表写几个类,继承父类 DataSupport,写getter和setter什么的,然后进行操作时,调用DataSupport的find、where功能..因为太过简便,让我觉得十分强大!

2、xml界面:
一个是关于framelayout布局里面从下至上依次放置左滑选择城市菜单、背景图片、SwipeRefreshLayout、ScrollView,使得UI界面十分生动
这里写图片描述
代码如下:

<FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.msi.coolweather.WeatherActivity"
    android:background="@color/colorPrimary">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <ImageView
            android:id="@+id/bing_pic_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop" />
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


    <ScrollView
        android:id="@+id/weather_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="none"
        android:overScrollMode="never">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true">
            <include layout="@layout/title"></include>
            <include layout="@layout/now"></include>
            <include layout="@layout/forecast"></include>
            <include layout="@layout/aqi"></include>
            <include layout="@layout/suggestion"></include>
        </LinearLayout>
    </ScrollView>

    </android.support.v4.widget.SwipeRefreshLayout>

        <fragment
            android:id="@+id/choose_area_fragment"
            android:name="com.example.msi.coolweather.ChooseAreaFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"></fragment>
    </android.support.v4.widget.DrawerLayout>
</FrameLayout>

3、关于网页请求
写了sendOkHttpRequest方法对网页发送请求

 public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(address).build();
        client.newCall(request).enqueue(callback);
    }

这是一个典型的Okhttp3的网页请求代码。
对address的Url发送请求,
返回的数据用handle来进行JSON处理

 //解析天气JSON数据
    public static Weather handleWeatherResponse(String response){
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
            String weatherContent = jsonArray.getJSONObject(0).toString();
            return new Gson().fromJson(weatherContent,Weather.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

4、后台更新服务:
重写onStartCommand每次开始时更新图片和天气,并且每隔8小时更新一次(如果用户不使用的时候)

 public int onStartCommand(Intent intent, int flags, int startId) {
        updateWeather();
        updateBingPic();
        AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
        int anHour = 8 * 60 * 60 * 1000;  //8hour
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this,MyServiceAutoUpdateService.class);
        PendingIntent pi = PendingIntent.getService(this,0,i,0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        return super.onStartCommand(intent,flags,startId);
    }

    private void updateBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyServiceAutoUpdateService.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
            }
        });
    }

    private void updateWeather() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather",null);
        if(weatherString != null){
            Weather weather = Utility.handleWeatherResponse(weatherString);
            final String weatherId = weather.basic.weatherId;
            String weatherUrl = "http://guolin.tech/api/weather?ciatyid=?" +
                    weatherId + "&key=cd510ea531714e62a45fe41560a2ab54";
            HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseText = response.body().string();
                    Weather weather = Utility.handleWeatherResponse(responseText);
                    if(weather != null && "ok".equals(weather.status)){
                        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyServiceAutoUpdateService.this).edit();
                        editor.putString("weather",responseText);
                        editor.apply();
                    }
                }
            });
        }
    }

其他的都是比较通俗易懂的

猜你喜欢

转载自blog.csdn.net/rikkatheworld/article/details/79706478
今日推荐