Android程序——天气预报

本文介绍了一款使用Android Studio开发的天气预报APP,通过选择城市获取天气、湿度、风向等信息。设计风格青春,功能包括主页、关注和搜索。采用Java、XML和和风天气API,提供实时及未来天气预测,便于用户出行规划。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随着移动通信技术的发展和无线数据业务的进步,手机已被赋予了通话意外的其他许多功能。

本设计使用安卓 Android studio 设计技术开发了一种运用在 android 系统上的手机天气预报软件系统,本系统通过选择城市来获得天气,空气指数、气温等信息。基于手机的天气预报系统软件可以使用户对于各个天气预报情况的实时掌握,极大的方便了用户的出行和行程安排,避免了不必要的麻烦,具有很强的实用性。

关键词:Android studio、安卓、天气预报系统、天气预报

  • 程序设计思路APP 的主题与名称 

天气是能决定许多人一天情绪和日常关注的问题,在以前,许多因为突如其来的坏天气而让农作物被毁,以及在晴天时晾晒衣物,却被突如其来的磅礴大雨全部打湿。所以一款准确的天气预报的程序是非常需要的,“Weather Of Gu” app,是一款能够实时预知天气,以及预知未来天气的app,因本人姓氏原因,所以将软件命名为:“Weather Of Gu”。

APP 的页面设计 

根据当下年轻人的风格,程序使用相对青春的设计思路,大部分由ICON矢量图实现,界面简洁但又不能失去功能的完整性。

功能的设计

  1. 主页:用户能通过主页,知道当前的气温、湿度、天气情况、风力与风向,并且能够看见未来几天的天气情况和气温等。
  2. 关注:在当前选择的城市左上角,用户可以通过点击加号查询家人的城市,以及亲朋好友的城市方便用户能够快速进行查看。
  3. 主页列表:主页列表是用户当前城市,用户可以在这里看见当前所在城市当前的天气情况以及气温,还有湿度、生活指数还有未来七日的天气情况

编写软件:Android studio

使用技术:Java,xml,和风天气官方 API 接口,JSON

  1. 欢迎界面

XML

<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="@drawable/imag3"
    tools:context=".activity.MainActivity">


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:gravity="center"
            android:text="Weather Of Gu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>


</FrameLayout>
  1. 主页

和风天气官网

Xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".activity.WeatherActivity"
    android:background="@drawable/img1">


    <ImageView
        android:id="@+id/bing_pic_img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager_weather"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="55dp">
    </androidx.viewpager.widget.ViewPager>


    <androidx.swiperefreshlayout.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="match_parent"
            android:layout_height="match_parent"
            android:overScrollMode="never"
            android:scrollbars="none">

            <LinearLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:orientation="vertical">

                <include layout="@layout/title" />
                <!--                    <include layout="@layout/title" />-->

                <include layout="@layout/now" />


                <include layout="@layout/aqi" />


                <include layout="@layout/forecast" />

                <include layout="@layout/suggestion" />

            </LinearLayout>

        </ScrollView>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    <LinearLayout
        android:id="@+id/ll_round"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:layout_marginBottom="7dp"
        android:orientation="horizontal"
        android:layout_alignBottom="@id/bing_pic_img"
        android:layout_centerInParent="true"
        android:gravity="bottom" />

</RelativeLayout>
  1. 搜索界面

Xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/imag2"
    android:orientation="vertical"
    tools:context=".activity.SearchActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="44dp"
        >

        <ImageView
            android:id="@+id/iv_search_back"
            android:layout_width="38dp"
            android:layout_height="match_parent"
            android:layout_centerVertical="true"
            android:paddingEnd="10dp"
            android:paddingStart="16dp"
            android:src="@mipmap/icon_back"
            android:paddingRight="10dp"
            android:paddingLeft="16dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="添加城市"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rv_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!--        自动完成文本框-->
        <AutoCompleteTextView
            android:id="@+id/et_search"
            android:layout_width="382dp"
            android:layout_height="83dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="25dp"
            android:gravity="center_vertical"
            android:hint="添加城市"
            android:maxLength="20"
            android:paddingStart="30dp"
            android:paddingLeft="30dp"
            android:singleLine="true"
            android:textColor="#ffffff"
            android:textColorHint="#ffffff"
            android:textSize="20sp" />

        <ImageView
            android:layout_width="14dp"
            android:layout_height="14dp"
            android:layout_centerVertical="true"
            android:layout_marginStart="24dp"
            android:layout_marginLeft="24dp"
            android:src="@mipmap/icon_search" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/ll_history"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:textColorHint="#ffffff"
            android:text="最近搜索"
            android:layout_marginLeft="16dp" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycle_history"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </androidx.recyclerview.widget.RecyclerView>
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycle_search"
        android:visibility="visible"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#ffffff"
        android:layout_marginTop="15dp">

    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

  • 部分代码详细介绍

MainActivity.Java:
public class MainActivity extends AppCompatActivity {

    final int REQUEST_PERMISSION_LOCATION = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPermission();
    }

    private void initPermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // 没得权限
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.READ_PHONE_STATE},
                    REQUEST_PERMISSION_LOCATION);
        } else {
            startService(new Intent(this, AMapService.class));
            startActivity();
//            stopService(new Intent(this,AMapService.class));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_LOCATION:
                startService(new Intent(this, AMapService.class));
//                stopService(new Intent(this,AMapService.class));
                startActivity();
                break;
            default:
                startActivity();
//                stopService(new Intent(this,AMapService.class));
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void startActivity() {
        startActivity(new Intent(this, WeatherActivity.class));
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this,AMapService.class));
    }
}

这是一个Android应用程序的MainActivity类,其中包含了一个initPermission()方法,用于检查应用程序是否已经获得了所需的权限。如果应用程序没有获得所需的权限,则会向用户请求这些权限。

在onCreate()方法中,调用了initPermission()方法来初始化权限。如果应用程序已经获得了所需的权限,则启动AMapService服务并启动地图活动。否则,向用户请求这些权限。

它定义了一个名为startActivity()的方法,该方法启动了一个名WeatherActivity的Activity,并在启动后立即销毁当前Activity。

另外,该类还重写了onDestroy()方法,在该方法中停止了名为AMapService的服务。

  1. SearchActivity.Java:
public class SearchActivity extends AppCompatActivity {

    private static final String TAG = "SearchActivity.class";

    private AutoCompleteTextView autoCompleteTextView;
    private LinearLayout linearLayout;
    private RecyclerView recyclerView;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        init();
        initSearch();

        imageView.setOnClickListener(v -> {
            if (v.getId() == R.id.iv_search_back) {
                onBackPressed();
            }
        });
    }


    private void init() {
        imageView = findViewById(R.id.iv_search_back);
        autoCompleteTextView = findViewById(R.id.et_search);
        linearLayout = findViewById(R.id.ll_history);
        recyclerView = findViewById(R.id.recycle_search);
        LinearLayoutManager sevenManager = new LinearLayoutManager(this);
        sevenManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(sevenManager);

    }

    String location = "null";

    private void initSearch() {
        autoCompleteTextView.setThreshold(1);
        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String input = autoCompleteTextView.getText().toString();
                if (!TextUtils.isEmpty(input)) {
                    linearLayout.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);

                    QWeather.getGeoCityLookup(SearchActivity.this, input, new QWeather.OnResultGeoListener() {
                        @Override
                        public void onError(Throwable throwable) {
                            runOnUiThread(() -> {
                                Toast.makeText(SearchActivity.this, input, Toast.LENGTH_SHORT).show();

                            });
                            Log.i(TAG, "getGeoCityLookup onError: " + throwable);
                        }

                        @Override
                        public void onSuccess(GeoBean geoBean) {
                            Log.i(TAG, "getGeoCityLookup onSuccess: " + new Gson().toJson(geoBean));
                            Map<String, Object> map = new HashMap<>();
                            if (Code.OK == geoBean.getCode()) {
                                List<GeoBean.LocationBean> locationBean = geoBean.getLocationBean();
                                List<City> cityList = new ArrayList<>();
                                if (locationBean != null && locationBean.size() > 0) {
                                    if (cityList.size() > 0) {
                                        cityList.clear();
                                    }
                                    for (int i = 0; i < locationBean.size(); i++) {
                                        GeoBean.LocationBean locationBeanData = locationBean.get(i);
                                        String name = locationBeanData.getName() + "-" + locationBeanData.getAdm2() + "-" + locationBeanData.getAdm1();
                                        String adm2 = locationBeanData.getAdm2();
                                        String adm1 = locationBeanData.getAdm1();
                                        String country = locationBeanData.getCountry();
                                        if (TextUtils.isEmpty(name)) {
                                            name = adm2;
                                        }
                                        if (TextUtils.isEmpty(adm2)) {
                                            name = adm1;
                                        }
                                        City city = new City();
                                        city.setId(locationBeanData.getId());
                                        city.setCityName(name);
                                        city.setGetAdm2(adm2);
                                        city.setGetAdm1(adm1);
                                        city.setGetCountry(country);
                                        Log.i("Asdd",city.toString());
                                        cityList.add(city);
                                    }

                                    SearchAdapter searchAdapter = new SearchAdapter(cityList, SearchActivity.this, autoCompleteTextView.getText().toString(), true);
                                    recyclerView.setAdapter(searchAdapter);
                                    searchAdapter.notifyDataSetChanged();
                                }


                            } else {
                                Code code = geoBean.getCode();
                                Log.i(TAG, "failed code: " + code);
                            }
                        }
                    });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }



}

初始化一个自动完成TextView并监听它的文本变化事件。在initSearch()方法中,首先调用autoCompleteTextView.setThreshold来设置自动完成TextView的最小字符数。然后,调用autoCompleteTextView.addTextChangedListener()来监听TextView的文本变化事件。

当TextView的文本发生变化时,会触发onTextChanged()方法。在onTextChanged()方法中,首先获取当前TextView的文本,然后判断文本是否为空。如果文本不为空,则将LinearLayout隐藏,将RecyclerView显示出来。

接下来,调用QWeather.getGeoCityLookup()方法来获取地理位置信息。如果获取失败,则使用Toast提示用户。如果获取成功,则将地理位置信息转换为City对象列表,并将其存储到cityList中。

最后,将City对象列表传递给SearchAdapter,并将其设置到RecyclerView的适配器中。同时,将自动完成TextView的文本设置为适配器中的搜索关键字。

  1. WeatherActivity.Java:
public class WeatherActivity extends AppCompatActivity  {

    private static final String TAG = "WeatherActivity.class";

    private final int REQUEST_GPS = 1;
    private int mNum = 0;

    private List<Fragment> fragments;
    CityList cityList = new CityList();
    private List<String> locaitons;
    private List<String> cityIds;
    private LinearLayout llRound;


    public SwipeRefreshLayout swipeRefresh;
    private ImageView navButton;
    private TextView titleCity;
    private TextView degreeText;
    private TextView weatherInfoText;
    private TextView cloudageText;
    private TextView humidityText;
    private LinearLayout forecastLayout;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;
    private ImageView backBingImg;
    private ProgressBar progressBar;
    private TextView progressBar_text;
    private TextView gradle_air_text;
    private TextView traffic_text;
    private TextView fish_text;
    private TextView travel_text;



    private LinearLayout linearLayout;

    private int[] image = {R.mipmap.cloudy, R.mipmap.fine, R.mipmap.rain, R.mipmap.thunder, R.mipmap.dawu, R.mipmap.haze, R.mipmap.fog};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        init();
//        initFragment();
        loadBingPic();
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_GPS);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        requestWeather(CommonUtil.CITY_ID);
        swipeRefresh.setOnRefreshListener(() -> {
            requestWeather(CommonUtil.CITY_ID);
            loadBingPic();
        });
        navButton.setOnClickListener(v->{
            if (v.getId() == R.id.nav_button) {
                startActivity(new Intent(this,SearchActivity.class));
            }
        });
    }



    public void init() {
        swipeRefresh = findViewById(R.id.swipe_refresh);
        titleCity = findViewById(R.id.title_city);
        degreeText = findViewById(R.id.degree_text);
        weatherInfoText = findViewById(R.id.weather_info_text);
        cloudageText = findViewById(R.id.cloudage_text);
        humidityText = findViewById(R.id.humidity_text);
        forecastLayout = findViewById(R.id.forecast_layout);
        comfortText = findViewById(R.id.comfort_text);
        carWashText = findViewById(R.id.car_wash_text);
        sportText = findViewById(R.id.sport_text);
        backBingImg = findViewById(R.id.bing_pic_img);
        swipeRefresh = findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
//        drawerLayout = findViewById(R.id.drawer_layout);
        navButton = findViewById(R.id.nav_button);
        progressBar = findViewById(R.id.progressBar);
        progressBar_text = findViewById(R.id.progressBar_text);
        gradle_air_text = findViewById(R.id.gradle_air);
        linearLayout = findViewById(R.id.linear);
        travel_text = findViewById(R.id.travel_text);
        fish_text = findViewById(R.id.fish_text);
        traffic_text = findViewById(R.id.traffic_text);
        navButton = findViewById(R.id.nav_button);

        llRound = findViewById(R.id.ll_round);
    }

    private void initFragment() {
        cityList = SpUtils.getBean(WeatherActivity.this, "cityBean", CityList.class);
        CityList cityBean = SpUtils.getBean(WeatherActivity.this, "cityBean", CityList.class);
        locaitons = new ArrayList<>();
        if (cityBean != null) {
            for (City city : cityBean.getCityBeans()) {
                String cityName = city.getCityName();
                locaitons.add(cityName);
            }
        }
        cityIds = new ArrayList<>();
        fragments = new ArrayList<>();
    }



    /**
     * 根据天气id查城市天气信息
     *
     * @param weatherId
     */
    public void requestWeather(final String weatherId) {

        /**
         * 实况天气数据
         * @param location 所查询的地区,可通过该地区名称、ID、IP和经纬度进行查询经纬度格式:经度,纬度
         *                 (英文,分隔,十进制格式,北纬东经为正,南纬西经为负)
         * @param lang     (选填)多语言,可以不使用该参数,默认为简体中文
         * @param unit     (选填)单位选择,公制(m)或英制(i),默认为公制单位
         * @param listener 网络访问结果回调
         */
        QWeather.getGeoCityLookup(WeatherActivity.this, CommonUtil.CITY_INITIAL, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable throwable) {
                runOnUiThread(() -> {
//                    Toast.makeText(WeatherActivity.this, CommonUtil.CITY_INITIAL, Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
                Log.i(TAG, "getGeoCityLookup onError: " + throwable);
            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                Log.i(TAG, "getGeoCityLookup onSuccess: " + new Gson().toJson(geoBean));

                if (Code.OK == geoBean.getCode()) {

                    List<GeoBean.LocationBean> locationBean = geoBean.getLocationBean();
                    List<City> cityBeans = new ArrayList<>();
                    City cityBean = new City();

                    for (GeoBean.LocationBean bean : locationBean) {
                        cityBean.setCityName(bean.getName());
                        System.out.println();
                        cityBean.setId(bean.getId());
                    }
                    if (cityList != null && cityList.getCityBeans() != null && cityList.getCityBeans().size() > 0) {
                        cityBeans = cityList.getCityBeans();
                        cityBeans.add(0, cityBean);
                    } else {
                        cityBeans.add(cityBean);
                    }
                    showWeather(geoBean,cityBeans,false);
                } else {
                    Code code = geoBean.getCode();
                    Log.i(TAG, "failed code: " + code);
                }
            }
        });

        QWeather.getWeatherNow(WeatherActivity.this, weatherId, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                System.out.println(weatherId + "---------weatherId");
                Log.i(TAG, "getWeather onSuccess: " + "*" + titleCity.getText() + " *" + new Gson().toJson(weatherBean));
                //先判断返回的status是否正确,当status正确时获取数据,若status不正确,可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    degreeText.setText(" " + now.getTemp() + "°");
                    weatherInfoText.setText(now.getText());

                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    Log.i(TAG, "failed code: " + code);
                }
            }
        });

        QWeather.getWeather7D(WeatherActivity.this, CommonUtil.CITY_ID, new QWeather.OnResultWeatherDailyListener() {
            @Override
            public void onError(Throwable throwable) {
                runOnUiThread(() -> {
//                    Toast.makeText(WeatherActivity.this, "获取未来七天天气信息失败", Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onSuccess(WeatherDailyBean weatherDailyBean) {
                List<WeatherDailyBean.DailyBean> daily = weatherDailyBean.getDaily();
                showWeather7d(daily);
            }
        });

        QWeather.getAirNow(WeatherActivity.this, CommonUtil.CITY_ID, Lang.ZH_HANS, new QWeather.OnResultAirNowListener() {
            @Override
            public void onError(Throwable throwable) {
                runOnUiThread(() -> {
//                    Toast.makeText(WeatherActivity.this, "获取空气信息失败", Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onSuccess(AirNowBean airNowBean) {
                if (airNowBean.getCode() == Code.OK) {
                    showAQIWeather(airNowBean);
                }

            }

        });

        QWeather.getWeather24Hourly(WeatherActivity.this, CommonUtil.CITY_ID, new QWeather.OnResultWeatherHourlyListener() {
            @Override
            public void onError(Throwable throwable) {
                runOnUiThread(() -> {
//                    Toast.makeText(WeatherActivity.this, "获取今日天气信息失败", Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }


            @Override
            public void onSuccess(WeatherHourlyBean weatherHourlyBean) {
                if (Code.OK == weatherHourlyBean.getCode()) {
                    List<WeatherHourlyBean.HourlyBean> hourly = weatherHourlyBean.getHourly();

                    getDayWeather(hourly);

                    Log.i(TAG, "getWeather24Hourly onSuccess: " + new Gson().toJson(hourly));
                } else {
                    Code code = weatherHourlyBean.getCode();
                    Log.i(TAG, "failed code: " + code);
                }
            }
        });

        List<IndicesType> list = new ArrayList<>();
        list.add(IndicesType.ALL);

        QWeather.getIndices1D(WeatherActivity.this, CommonUtil.CITY_ID, Lang.ZH_HANS, list, new QWeather.OnResultIndicesListener() {
            @Override
            public void onError(Throwable throwable) {
                runOnUiThread(() -> {
                    Log.i(TAG, "getIndices1D onError: " + throwable);
//                    Toast.makeText(WeatherActivity.this, "获取生活指数失败", Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onSuccess(IndicesBean indicesBean) {
                if (Code.OK == indicesBean.getCode()) {
                    List<IndicesBean.DailyBean> dailyList = indicesBean.getDailyList();
                    showIndexOfLive(dailyList);
                }
            }
        });
        swipeRefresh.setRefreshing(false);

    }


    private void showWeather(GeoBean geoBean, List<City> cityList, boolean first) {
        List<GeoBean.LocationBean> locationBean = geoBean.getLocationBean();
        GeoBean.LocationBean locationBean1 = locationBean.get(0);
        titleCity.setText(CommonUtil.CITY_INITIAL);
        CommonUtil.NOW_CITY_NAME = locationBean1.getName();
        CommonUtil.CITY_ID = locationBean1.getId();

    }


    private void showWeather7d(List<WeatherDailyBean.DailyBean> daily) {
        forecastLayout.removeAllViews();
        for (WeatherDailyBean.DailyBean dailyBean : daily) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
            TextView dataText = view.findViewById(R.id.date_text);
            TextView infoText = view.findViewById(R.id.info_text);
            TextView maxText = view.findViewById(R.id.max_text);
            TextView minText = view.findViewById(R.id.min_text);
//          显示周
            dataText.setText(WeekUtil.dateToWeek(dailyBean.getFxDate()));
            // 显示日期
//            dataText.setText(dailyBean.getFxDate());
            infoText.setText(dailyBean.getTextDay());
            maxText.setText(dailyBean.getTempMax());
            minText.setText(dailyBean.getTempMin());
            forecastLayout.addView(view);
        }

        String tempMax = daily.get(0).getTempMax();
        String tempMin = daily.get(0).getTempMin();
        cloudageText.setText("最高: " + tempMax + "° ");
        humidityText.setText("  最低: " + tempMin + "°");

    }

    private void showAQIWeather(AirNowBean airNowBean) {
        AirNowBean.NowBean now = airNowBean.getNow();
        String aqi = now.getAqi();
        int aqi_int = Integer.parseInt(aqi);
        progressBar.setMax(500);
        progressBar.setProgress(aqi_int);
        progressBar_text.setText(" AQI " + aqi + " ");
        if (aqi_int > 300) {
            gradle_air_text.setText("严重污染");
        } else if (aqi_int > 200 && aqi_int <= 300) {
            gradle_air_text.setText("重度污染");
        } else if (aqi_int > 150 && aqi_int <= 200) {
            gradle_air_text.setText("中度污染");
        } else if (aqi_int > 100 && aqi_int <= 150) {
            gradle_air_text.setText("轻度污染");
        } else if (aqi_int > 50 && aqi_int <= 100) {
            gradle_air_text.setText("良");
        } else {
            gradle_air_text.setText("优");
        }
    }

    /**
     * 如果加载不出来,应该是电脑和调试机连接了不同的wifi或网络
     */
    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                runOnUiThread(() -> Glide.with(WeatherActivity.this).load(bingPic).into(backBingImg));
            }

            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {View view = getWindow().getDecorView();
                view.setBackgroundResource(R.drawable.img1);});
            }
        });
    }


    private void getDayWeather(List<WeatherHourlyBean.HourlyBean> hourly) {
        linearLayout.removeAllViews();
        for (WeatherHourlyBean.HourlyBean hourlyBean : hourly) {
            View view = LayoutInflater.from(this).inflate(R.layout.day_weather_item, linearLayout, false);
            TextView day_weather_text = view.findViewById(R.id.day_weather_text);
            ImageView img_dayweather = view.findViewById(R.id.img_dayweather);
            TextView text_weather_temperature = view.findViewById(R.id.text_weather_temperature);
            String fxTime = hourlyBean.getFxTime();
            String substring = fxTime.substring(11, 16);
            day_weather_text.setText(substring);
            if (hourlyBean.getText().contains("云")) {
                img_dayweather.setImageResource(image[0]);
            } else if (hourlyBean.getText().contains("晴")) {
                img_dayweather.setImageResource(image[1]);
            } else if (hourlyBean.getText().contains("雨")) {
                img_dayweather.setImageResource(image[2]);
            } else if (hourlyBean.getText().contains("雷")) {
                img_dayweather.setImageResource(image[3]);
            } else if (hourlyBean.getText().contains("霾")) {
                img_dayweather.setImageResource(image[4]);
            } else if (hourlyBean.getText().contains("雾")) {
                img_dayweather.setImageResource(image[5]);
            } else {
                img_dayweather.setImageResource(image[6]);
            }
            text_weather_temperature.setText(hourlyBean.getTemp() + "°");
            linearLayout.addView(view);
        }
    }

    private void showIndexOfLive(List<IndicesBean.DailyBean> dailyList) {

        traffic_text.setText(dailyList.get(1).getName() + ": " +dailyList.get(1).getText());
        travel_text.setText(dailyList.get(5).getName() + ": " + dailyList.get(5).getText());
        comfortText.setText(dailyList.get(4).getName() + ": " + dailyList.get(4).getText());
        carWashText.setText(dailyList.get(15).getName() + ": " + dailyList.get(15).getText());
        sportText.setText(dailyList.get(6).getName() + ": " + dailyList.get(6).getText());
        fish_text.setText(dailyList.get(3).getName() + ": " + dailyList.get(3).getText());
    }
}

在onCreate()中调用父类的onCreate()方法,并将savedInstanceState参数传递给它。

设置Activity的布局视图,这里使用了activity_weather.xml布局文件。请求地理位置权限,如果用户拒绝权限请求,将显示权限请求对话框。请求天气信息,并传递CommonUtil.CITY_ID作为参数。设置下拉刷新的刷新监听器,当用户下拉刷新时,会重新请求天气信息背景图片。为导航按钮设置点击监听器,当用户点击按钮时,会启动SearchActivity。

私有方法initFragment(),使用SpUtils.getBean()方法从SharedPreferences中获取名为"cityBean"的CityList对象,并将其赋值给cityList变量。再次使用SpUtils.getBean()方法从SharedPreferences中获取名为"cityBean"的CityList对象,并将其赋值给cityBean变量。创建一个名为locaitons的ArrayList对象,用于存储城市名称。如果cityBean不为空,则遍历其中的每个City对象,并将其城市名称添加到locaitons列表中。创建一个名为cityIds的ArrayList对象,用于存储城市ID。创建一个名为fragments的ArrayList对象,用于存储Fragment对象

Android Studio可以通过调用第三方天气API来实现天气预报功能。以下是实现步骤: 1. 在Android Studio中创建一个新项目。 2. 在项目中添加网络权限,以便从API获取数据。 3. 在布局文件中添加一个TextView,用于显示天气信息。 4. 在MainActivity.java文件中,使用Volley库或OkHttp库从API获取天气数据。 5. 解析API响应并将其显示在TextView中。 代码示例(使用Volley库): ```java // 添加Volley库依赖 implementation 'com.android.volley:volley:1.2.0' // 在MainActivity.java文件中 public class MainActivity extends AppCompatActivity { private TextView mWeatherTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWeatherTextView = findViewById(R.id.weather_text_view); // 使用Volley库从API获取天气数据 RequestQueue queue = Volley.newRequestQueue(this); String url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // 解析API响应并将其显示在TextView中 try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("weather"); JSONObject weatherObject = jsonArray.getJSONObject(0); String weatherDescription = weatherObject.getString("description"); mWeatherTextView.setText(weatherDescription); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mWeatherTextView.setText("Error"); } }); queue.add(stringRequest); } } ``` 注意:在上面的代码示例中,需要将YOUR_API_KEY替换为你自己的API密钥。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值