Androi天气

<?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:orientation="vertical"
    tools:context=".ui.me.WeatherFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/appintro_bar_color"
        android:gravity="center"
        android:text="天气"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_margin="20dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_margin="10dp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="50dp">

            <TextView
                android:id="@+id/province_tv"
                android:text="省份:"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>

            <EditText
                android:id="@+id/province_edit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/province_tv"
                android:hint="请输入要查询的天气的省份" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_margin="10dp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="50dp">

            <TextView
                android:id="@+id/city_tv"
                android:text="城市:"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>

            <EditText
                android:id="@+id/city_edit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/city_tv"
                android:hint="请输入该省份的城市" />

        </RelativeLayout>

        <Button
            android:id="@+id/search"
            android:text="查询"
            android:layout_alignParentRight="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <TextView
        android:id="@+id/city_weather"
        android:text="城市的天气"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:visibility="gone"/>

    <LinearLayout

        android:id="@+id/weather_info"
        android:layout_margin="10dp"
        android:orientation="vertical"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:text="天气:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/weather"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <LinearLayout

            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:text="湿度:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/shidu"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:text="生活建议:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/suggestion"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
public class WeatherFragment extends Fragment implements View.OnClickListener {

    private String weatherCountry = "http://guolin.tech/api/china/";//中国的省份城市api
    private String weatherProvince, weatherCity;//获取到的省份id和城市id
    private ArrayList<Province> provinceList;//中国的省份集合
    private ArrayList<City> cityList;//具体省份的城市集合

    private String weatherUrl = "https://free-api.heweather.net/s6/weather/now?location=%s&key=%s";//和风天气 免费的api接口
    private String cityId;//具体城市天气id,如湛江,"weather_id"=CN101281001

    //注册和风天气开发者https://dev.heweather.com/
    //创建的apk 的 用户id 以及 该apk的key(包名要一致)
    private String userName = "HE2205202149311119";
    private String key = "4c0f7dccc80748e49e20d0b99f27c43c";//自己申请的key

    private EditText mCityEdit;
    /**
     * 查询
     */
    private Button mSearch;
    /**
     * 城市的天气
     */
    private TextView mCityWeather;
    private TextView mWeather;
    private TextView mShidu;
    /**
     * 省份:
     */
    private TextView mProvinceTv;
    /**
     * 请输入要查询的天气的省份
     */
    private EditText mProvinceEdit;

    String province, city;//接收输入的省份和城市收用的字符串
    private LinearLayout mWeatherInfo;
    private TextView mSuggestion;
    private String TAG = "WeatherFragment";


    private LocationClient mLocationClient = null;




    @Override
    public void onDestroy() {
        mLocationClient.stop();
        super.onDestroy();

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLocationListenner myListener = new MyLocationListenner();

        mLocationClient = new LocationClient(getContext());

        LocationClientOption option = new LocationClientOption();

        option.setIsNeedAddress(true);

        option.setAddrType("all");

        mLocationClient.setLocOption(option);

        mLocationClient.registerLocationListener(myListener);

        mLocationClient.start();
    }

    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            try {
                String province = location.getProvince();
                String city = location.getCity();
                mCityEdit.setText(city.substring(0,city.length()-1));
                mProvinceEdit.setText(province.substring(0,province.length()-1
                ));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        //        使用 SDK 时,需提前进行账户初始化(全局执行一次即可)
        HeConfig.init(userName, key);
//        个人开发者、企业开发者、普通用户等所有使用免费数据的用户需要切换到免费服务域名 即 https://free-api.heweather.net/s6/sdk/
        HeConfig.switchToFreeServerNode();

        View root=inflater.inflate(R.layout.fragment_weather, container, false);
         initView(
                 root
         );
        return  root;
    }

    private void initView(View root) {
        mCityEdit = (EditText) root.findViewById(R.id.city_edit);
        mSearch = (Button) root.findViewById(R.id.search);
        mSearch.setOnClickListener(this);
        mCityWeather = (TextView) root.findViewById(R.id.city_weather);
        mWeather = (TextView) root.findViewById(R.id.weather);
        mShidu = (TextView) root.findViewById(R.id.shidu);
        mProvinceTv = (TextView) root.findViewById(R.id.province_tv);
        mProvinceEdit = (EditText) root.findViewById(R.id.province_edit);
        mWeatherInfo = (LinearLayout) root.findViewById(R.id.weather_info);
        mSuggestion = (TextView) root.findViewById(R.id.suggestion);
    }

    public void onClick(View v) {
        System.out.println("111");
        switch (v.getId()) {
            default:
                break;
            case R.id.search:
                province = mProvinceEdit.getText().toString().trim();
                city = mCityEdit.getText().toString().trim();
                queryWeather();
                break;
        }
    }

    private void queryWeather() {
        provinceList = new ArrayList<Province>();//省份集合
        cityList = new ArrayList<City>();//具体省份的城市集合
        new Thread() {
            @Override
            public void run() {
                try {
                    //weatherCountry = "http://guolin.tech/api/china/"
                    URL url = new URL(weatherCountry);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启一个url的连接,用HttpURLConnection连接方式处理
                    connection.setRequestMethod("GET");//设置连接对象的请求数据的方式
                    connection.setConnectTimeout(3000);//设置连接对象的请求超时的时间

                    //将请求返回的数据流转换成字节输入流对象
                    InputStream is = connection.getInputStream();
                    //将字节输入流对象转换成字符输入流对象
                    InputStreamReader isr = new InputStreamReader(is);
                    //创建字符输入缓冲流对象
                    BufferedReader br = new BufferedReader(isr);

                    StringBuffer sb = new StringBuffer();
                    String string;

                    //读文本
                    while ((string = br.readLine()) != null) {
                        sb.append(string);
                    }

                    String result = sb.toString();

                    Log.d("WeatherFragment", "" + result);


                    JSONArray provinceArray = new JSONArray(result);
                    for (int i = 0; i < provinceArray.length(); i++) {
                        JSONObject provinceInfo = provinceArray.getJSONObject(i);//获取每个省份信息
                        Province provinceBean = new Province();//创建省份实体类对象
                        Gson gson = new Gson();//创建Gson解析对象

                        //反序例化,将json数据转化为实体类对象的成员变量值
                        provinceBean = gson.fromJson(provinceInfo.toString(), Province.class);
                        //添加保存好的省份对象数据进入省份集合
                        provinceList.add(provinceBean);
                    }

                    for (Province pro : provinceList) {
                        //如果该省份为用户输入的省份
                        if (pro.getName().equals(province)) {
                            //则拼接链接
                            //如:北京 weatherProvince = "http://guolin.tech/api/china/1/"
                            weatherProvince = weatherCountry + pro.getId() + "/";
                        }
                    }

                    Log.d("WeatherProvince", "" + weatherProvince);

                    //如:北京 weatherProvince = "http://guolin.tech/api/china/1/"
                    url = new URL(weatherProvince);
                    connection = (HttpURLConnection) url.openConnection();//开启一个url的连接用HttpURLConnection连接方式处理
                    connection.setRequestMethod("GET");//设置连接对象的请求数据的方式
                    connection.setConnectTimeout(3000);//设置连接对象的请求超时的时间

                    //将请求返回的数据流转换成字节输入流对象
                    is = connection.getInputStream();
                    //将字节输入流对象转换成字符输入流对象
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);

                    StringBuffer sb2 = new StringBuffer();
                    //读文本
                    while ((string = br.readLine()) != null) {
                        sb2.append(string);
                    }

                    String result2 = sb2.toString();

                    Log.d("MainActivity2", "" + result2);

                    JSONArray cityArray = new JSONArray(result2);
                    for (int i = 0; i < cityArray.length(); i++) {
                        JSONObject cityInfo = cityArray.getJSONObject(i);//获取具体省份城市信息
                        City cityBean = new City();//创建城市实体类对象
                        Gson gson = new Gson();//创建Gson解析对象
                        //反序例化,将json数据转化为实体类对象的成员变量值
                        cityBean = gson.fromJson(cityInfo.toString(), City.class);
                        //添加保存好的城市对象数据进入城市集合
                        cityList.add(cityBean);
                    }

                    for (City c : cityList) {
                        //如果该城市为用户输入的城市
                        if (c.getName().equals(city)) {
                            //则拼接链接
                            //如:北京 weatherCity = "http://guolin.tech/api/china/1/1/"
                            weatherCity = weatherProvince + c.getId() + "/";
                        }
                    }

                    Log.d("WeatherCity", ""+weatherCity);

                    //如:北京 weatherCity = "http://guolin.tech/api/china/1/1/"
                    url = new URL(weatherCity);
                    connection = (HttpURLConnection) url.openConnection();//开启一个url的连接用HttpURLConnection连接方式处理
                    connection.setRequestMethod("GET");//设置连接对象的请求数据的方式
                    connection.setConnectTimeout(3000);//设置连接对象的请求超时的时间

                    //将请求返回的数据流转换成字节输入流对象
                    is = connection.getInputStream();
                    //将字节输入流对象转换成字符输入流对象
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);

                    StringBuffer sb3 = new StringBuffer();
                    //读文本
                    while ((string = br.readLine()) != null) {
                        sb3.append(string);
                    }

                    String result3 = sb3.toString();

                    Log.d("MainActivity3", "" + result3);

                    JSONArray jsonArray = new JSONArray(result3);
                    JSONObject cityIdInfo = jsonArray.getJSONObject(0);
                    cityId=cityIdInfo.getString("weather_id");

                    //拼接字符串
                    String weatherApi = String.format(weatherUrl, cityId, key);
                    Log.d("WeatherApi", "" + weatherApi);
                    queryWeather2();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }


    public void queryWeather2(){
        /**
         * 实况天气
         * 实况天气即为当前时间点的天气状况以及温湿风压等气象指数,具体包含的数据:体感温度、
         * 实测温度、天气状况、风力、风速、风向、相对湿度、大气压强、降水量、能见度等。
         *
         * @param context  上下文
         * @param location 地址详解
         * @param lang     多语言,默认为简体中文,海外城市默认为英文
         * @param unit     单位选择,公制(m)或英制(i),默认为公制单位
         * @param listener 网络访问回调接口
         */
        HeWeather.getWeatherNow(getContext(), cityId, Lang.CHINESE_SIMPLIFIED , Unit.METRIC , new HeWeather.OnResultWeatherNowBeanListener() {
            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "Weather Now onError: ", e);
            }

            @Override
            public void onSuccess(Now dataObject) {
                Log.i(TAG, " Weather Now onSuccess: " + new Gson().toJson(dataObject));
                //先判断返回的status是否正确,当status正确时获取数据,若status不正确,可查看status对应的Code值找到原因
                if ( Code.OK.getCode().equalsIgnoreCase(dataObject.getStatus()) ){
                    //此时返回数据

                    Basic basic=dataObject.getBasic();
                    String location=basic.getLocation();

                    mCityWeather.setText(location+"的天气");

                    NowBase now = dataObject.getNow();

                    String tmp=now.getTmp();
                    String cond_txt=now.getCond_txt();
                    String wind_dir=now.getWind_dir();

                    mWeather.setText("当前温度:"+tmp+"℃,"+cond_txt+","+wind_dir);
                    String hum=now.getHum();
                    mShidu.setText(hum+"%");
                } else {
                    //在此查看返回数据失败的原因
                    String status = dataObject.getStatus();
                    Code code = Code.toEnum(status);
                    Log.i(TAG, "failed code: " + code);
                }
            }
        });
        HeWeather.getWeatherLifeStyle(getContext(),cityId, new HeWeather.OnResultWeatherLifeStyleBeanListener() {
            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onSuccess(Lifestyle lifestyle) {
                List<LifestyleBase> lifestyleBases=lifestyle.getLifestyle();
                String shushidu=lifestyleBases.get(0).getBrf();//舒适度指数
                String shushidu2=lifestyleBases.get(0).getTxt();//舒适度建议
                String sport=lifestyleBases.get(3).getBrf();//运动指数
                String sport2=lifestyleBases.get(3).getTxt();//运动建议
                String cw=lifestyleBases.get(6).getBrf();//洗车指数
                String cw2=lifestyleBases.get(6).getTxt();//洗车建议
                System.out.println("sdfsdf");
                mSuggestion.setText("舒适度指数:"+shushidu+"\n" +
                        "舒适度建议:"+shushidu2+"\n" +
                        "运动指数:"+sport+"\n" +
                        "运动建议:"+sport2+"\n" +
                        "洗车指数:"+cw+"\n" +
                        "洗车建议:"+cw2+"\n");
                mCityWeather.setVisibility(View.VISIBLE);
                mWeatherInfo.setVisibility(View.VISIBLE);


            }

        });


    }



}
public class Province {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class City {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".ui.video.VideoFragment" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:gravity="center"
        android:orientation="vertical"
        android:background="@color/purple_500">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/circleImageView"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@drawable/default_head"
            app:civ_border_color="#fff"
            app:civ_border_width="2dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击登录"
            android:textColor="#fff"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

    </LinearLayout>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        android:layout_margin="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/linearLayout_run"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/calendar_icon" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="日历" />
            </LinearLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="#ebebeb" />

            <LinearLayout
                android:id="@+id/linearLayout_star"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/constellation_icon" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="星座" />
            </LinearLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="#ebebeb" />

            <LinearLayout
                android:id="@+id/linearLayout_ty"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/scraw_icon" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="涂鸦" />
            </LinearLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="#ebebeb" />

            <LinearLayout
                android:id="@+id/linearLayout_map"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/map_icon" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="地图" />
            </LinearLayout>

        </LinearLayout>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        android:layout_margin="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/linearLayout_weather"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/collection_icon" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="天气"
                    android:layout_marginStart="10dp"/>

                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    app:srcCompat="@drawable/iv_right_arrow" />
            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#ebebeb"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/setting_icon" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="设置"
                    android:layout_marginStart="10dp"/>

                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    app:srcCompat="@drawable/iv_right_arrow" />
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值