How to know the weather

preface

Project: github.com/w77996/Weat…

Know more about the weather, the code is not good, mainly for everyone to learn. Some of the stuff was borrowed from other people, mostly from other people’s UI, because I wrote the UI so bad TAT that I couldn’t read it myself.

The project was mainly set up on December 23, and I went back home for more than half a month during the Spring Festival. The whole project was completed in early March. It took nearly two months. Usually in the company also do some testing tasks, development tasks will not be until after graduation TAT I don’t know after graduation will be retained, so it is also a practice. I also wrote an HTTP +Mvp reading APP based on Rxjava+Retrofif+Ok. The link is here: HiReader. The project has not been completed yet, and it has been updated all the time, mainly learning some mainstream things by myself.


Thanks to the open source

Watching other people’s code slowly learning, you will see your own growth ~ Now I think this graduation project is not as difficult as I thought at first, I can use a higher efficiency, a better way to achieve the project.

Borrowed projects

Depending on the weather

High imitation yahoo weather

There is guo God’s second line of code, do not explain

Open source framework

  • Butterknife annotation type frame jakewharton. Making. IO/Butterknife…
  • Glide picture loading framework github.com/bumptech/gl…
  • Okhttp Network request framework square.github. IO/Okhttp /
  • LitePal database operation framework github.com/LitePalFram…
  • Logger development log framework github.com/orhanobut/l…
  • Gson JSON data parsing framework github.com/google/gson
  • SlidingMenu Side pull menu frame github.com/jfeinstein1…
  • SwipeMenuListView Delete frame github.com/baoyongzhan…
  • Weather data provided by Easy Source data www.showapi.com/
  • The aurora push service www.jiguang.cn/accounts/pl…
  • There is rice advertising platform www.youmi.net/
  • Amap lbs.amap.com/

function

  1. Open the APP boot page for the first time and buffer loading
  2. Display of weather information
  3. Advertising, push
  4. Desktop gadget
  5. News information viewing
  6. Bluetooth serial port transmits temperature

At that time, Gson was not very popular, and it was a failure of Android development. It was stupid to parse thousands of JSON messages by yourself.

To prepare

Weather Json in easy source data if the request is 15 days of Json data there are nearly a thousand lines, so fetch your own useful Json.

  • Development environment: Android Studio
  • Data acquisition: Easy source data SDK

    Help tool

    Json online parsing

Easy source data official website


Json data analysis





image

So much Json, too scary to think about, but let’s go step by step, the role of key can see the easy source of the document.

  1. CityInfo City information
  2. Time time
  3. What is the weather now
  4. F1 ~ F6 weather forecast information for nearly one week
  5. AlarmList Indicates alarm information
  6. HourDataList Weather updates every half hour
  7. Aqi Air quality

The weather is encapsulated

Create com.weather.entity under the directory

Actually, I think Gson is quite useful… So why don’t I use Gson… Since @serializedName was not used at that time, json of easy source data should have a key starting with a number ┭┮﹏┭┮

Then after a lot of inversion, finally put the data to = =, as their own parsing JSON data practice

Network request

Mainly using OKHTTP, using a few lines of code by Guo Shen

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

You just pass in the address and you get the data,

But there is a pothole!! There’s a pit!!

There’s a pit!!

Important things are done three times

Response.body ().string() cannot be used directly after the request.

  // Use the okHTTP wrapper for the request
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // There are pits
                String responseText = response.body().string();Copy the code

The database

My database super bad, but not slag, or can write something, the database I design is very simple, only two important attributes, is the city name and JSON data, in order to get json data directly from the database in the state of no network, after parsing display to the interface. I was going to use GreenDao for the frame, but I changed it to LitePal.

public class WeatherDB extends DataSupport {
    public int id;
    public String mCityName;
    public StringmJsonData; .Copy the code

Advertising, push

Advertising is rice advertising, directly against the SDK to add the code to go, want to use Tencent advertising, but call me to ask me whether I have a business license… Dizzy, did not have so did not approve.

Push using aurora push, also directly using SDK, originally used BOMB, but BOMB SDK OKHTTP and my own dependence conflict, and there are some machines can not push successfully, so finally changed to aurora push, this is bloody pit ah, step by step to just spit blood.

    // The banner is initialized
        View bannerView = BannerManager.getInstance(WeatherActivity.this)
                .getBannerView(WeatherActivity.this.new BannerViewListener() {
                    @Override
                    public void onRequestSuccess(a) {}
                    @Override
                    public void onSwitchBanner(a) {}
                    @Override
                    public void onRequestFailed(a) {}});// Get the layout to embed the banner
        LinearLayout bannerLayout = (LinearLayout) findViewById(R.id.ll_banner);
        // Add the banner to the layout
        bannerLayout.addView(bannerView);Copy the code

Embed advertisement is so simple and violent, but suggest to use integral wall, I this is an advertisement bar…

Because… They don’t seem to have any banners… It probably won’t show up in practice, but it will if you use the test ads during initialization.

City selection

Here recommend others write a dependency, direct portal CityPicker

Using Autonavi for location





image

Desktop gadget

I still have a lot to learn in this area. Start the service and update it in the background. Think about adding Rxjava in the future and see if I can optimize some operations.





image

   // Get the Image control from APPWIdgetTarget
                 mAppWidgetTarget =new AppWidgetTarget(getApplicationContext(),mRemoteViews.R.id.appwiget_picture.mAppwidgetId);
                Glide.with(getApplicationContext()).load(weatherBean.getmNowWeatherBean().getmWeather_Pic()).asBitmap().into(mAppWidgetTarget);Copy the code

Bluetooth and MCU communication module

Because I have learned embedded development, I came into contact with Android by chance, so now I do Android development, DS18B20 temperature sensor is used on the single chip microcomputer, Bluetooth is HC-05, temperature transmission through the serial port, do not think it is difficult, in fact, it is very simple, well, just kidding, it is very simple if the foundation is good. There are not many codes, I tried once and the returned data was always garbled, I searched for the problem for a week but couldn’t find it, finally I found it was the baud rate problem, I was so moved, portal

interface

Enter APP loading interface, fade in and out effect, weak reference holding Activity object, text animation effect





The buffer interface

  // The activity toggle fades in and out
       overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);Copy the code
// Use of weak references
 private static class SwitchHandler extends Handler {
        private WeakReference<SplashActivity> mWeakReference;

        SwitchHandler(SplashActivity activity) {
            mWeakReference = new WeakReference<SplashActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SplashActivity activity = mWeakReference.get();
            if(activity ! =null) {
                WeatherActivity.launch(activity); activity.finish(); }}}Copy the code

The main interface





image

In fact, the status bar is not transparent as required by Material Design. The main interface fills the entire mobile phone screen. By calculating the total height of the mobile phone screen and subtracting the height of the status bar and the height of the ActionBar, the height of the main interface view is obtained. This is how the screen looks at any resolution (forgive the awkward expression, just get the idea).

  /** * Get the phone screen height **@param context
     * @return* /
    public static int getDisplayHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        // Get screen information
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /** * Get the phone screen width **@param context
     * @return* /
    public static int getDisplayWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        // Get screen information
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /** * Reflection method to get the status bar height **@param context
     * @return* /
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 20;
        try{ Class<? > _class = Class.forName("com.android.internal.R$dimen");
            Object object = _class.newInstance();
            Field field = _class.getField("status_bar_height");
            int restult = Integer.parseInt(field.get(object).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(
                    restult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Toast.makeText(getActivity(), "StatusBarHeight = " + statusBarHeight,
        // Toast.LENGTH_SHORT).show();
        return statusBarHeight;
    }

    /** * get? Attr /actionBarSize Height * *@param context
     * @return* /
    public static int getActionBarSize(Context context) {
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.actionBarSize, typedValue, true);
        int actionBarHeight = TypedValue.complexToDimensionPixelSize(typedValue.data, context.getResources().getDisplayMetrics());
        return actionBarHeight;
    }
        // mNowWeatherHeight = Screen height - Title bar height - Status bar height
        mNowWeatherHeight = SystemUtils.getDisplayHeight(mContext) - SystemUtils.getActionBarSize(mContext) - SystemUtils.getStatusBarHeight(mContext);Copy the code

Updated data list and future weather forecast every half hour

Here is RecyclerView. The width of the screen is also calculated when drawing each Item. Each Item accounts for 1/5 of the screen, so only five items are presented under all resolutions





image

Air index and living index

A lot of UI is from Android Studio Vetor Assert inside to find, you can also go to find your own UI, as well as Alibaba iconFont Alibaba vector icon library





image

City editing interface

The background Activity is translucent, fills the screen, and the ListView slides to delete

After entering the Activity, obtain the data from the database and display it in the ListView. After the operation, obtain the content in the database again in the onActivityResult of the main interface and update the UI.





image

// Sideslip delete
SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9.0x3F.0x25)));
                deleteItem.setWidth(dp2px(60)); deleteItem.setIcon(R.drawable.ic_delete); menu.addMenuItem(deleteItem); }}; mCityEditListview.setMenuCreator(creator); mCityEditListview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        // open
                        Toast.makeText(getApplicationContext(), position + " menu click", Toast.LENGTH_SHORT).show();
                        if(mCityList.size(a) >1){
                            CityRmoveThread cityRmoveThread = new CityRmoveThread(mCityList.get(position).getmCityName());
                            cityRmoveThread.start();
                            mCityList.remove(position);
                            mCityEditListAdapter.notifyDataSetChanged();
                        }else{
                            Toast.makeText(getApplicationContext(), position + "Honey, deleted what are you looking at?", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
                // false: closes the menu; True: the menu will not be closed
                returnfalse; }});Copy the code

The news, the jokes, the pictures

This module is written to be honest, I can’t even read it, at that time in order to catch up with the schedule, ah, meaning. It’s very simple to store using SharePreference. Well, that’s it

conclusion

Is for reference only and shall not be used for commercial projects, if you feel you have help and give a Star kiss ~ when writing the program wrote a lot of details, forget a lot of, is to deal with some problems in ~ and guide page design is not very good, is directly deduct the picture on the network, to the third interface one click can go in ~ thanks for watching