“网络获取经纬度-->获取所在城市名-->获取该城市天气”一条龙搞定

要用到jackson json相关jar包,请自行下载,我已经上传到csdn,免费,需要的可以下载:

http://download.csdn.net/detail/ithouse/8787725

还要用到xUtils相关jar包(可选,由于根据城市名获取天气的方法要用到几个参数和设定返回编码,我直接用xUtils来完成了。),我也上传到了csdn,免费,需要的可以下载:

http://download.csdn.net/detail/ithouse/8787713

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itant.mycity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

布局文件:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.itant.mycity.MainActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

代码:

package com.itant.mycity;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class MainActivity extends Activity implements LocationListener {
    protected LocationManager locationManager;
    private TextView tv_city;
    private HttpUtils utf8Client;
    private String city;
    private String temperature;

    // 维度,经度
    private String URL_GET_CITY = "http://api.map.baidu.com/geocoder/v2/?ak=pmCgmADsAsD9rEXkqWNcTzjd&location=%s&output=json&pois=1";

    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            // TODO Auto-generated method stub

            tv_city.setText("您所在的城市是:" + city + "  当天温度:" + temperature);
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_city = (TextView) findViewById(R.id.textview1);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 500, 0, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        // 通过网络获取所在地的经纬度
        URL_GET_CITY = String.format(URL_GET_CITY, location.getLatitude() + "," + location.getLongitude());
        getCityName(URL_GET_CITY);
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Latitude", "disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Latitude", "enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude", "status");
    }

    /**
     * 调用百度的链接,根据维度和经度获取所在城市名
     * @param url
     */
    private void getCityName(final String url) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // 创建默认的客户端实例
                HttpClient httpCLient = new DefaultHttpClient();
                // 创建get请求实例
                HttpGet httpget = new HttpGet(url);
                try {
                    // 客户端执行get请求 返回响应实体
                    HttpResponse response = httpCLient.execute(httpget);

                    // 服务器响应状态行
                    //System.out.println(response.getStatusLine());

                    Header[] heads = response.getAllHeaders();
                    // 打印所有响应头
                    for (Header h : heads) {
                        System.out.println(h.getName() + ":" + h.getValue());
                    }

                    if (200 == response.getStatusLine().getStatusCode()) {
                        // 获取响应消息实体
                        HttpEntity entity = response.getEntity();

                        System.out.println("------------------------------------");

                        if (entity != null) {
                            ObjectMapper mapper = new ObjectMapper();
                            JsonNode jsonNode;
                            try {
                                jsonNode = mapper.readTree(EntityUtils.toString(entity));
                                city = jsonNode.get("result").get("addressComponent").get("city").textValue();
                                getCityWeather(city);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    httpCLient.getConnectionManager().shutdown();
                }
            }
        }).start();
    }

    /**
     * 调用百度的链接,根据城市名获取城市天气
     * @param city
     */
    private void getCityWeather(String city) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("location", city);
        params.addQueryStringParameter("ak", "2o5QP4AtEGZGKPz2LXQO2z4I");
        params.addQueryStringParameter("output", "json");
        try {
            if (utf8Client == null) {
                utf8Client = new HttpUtils();   
            }
            // 设置缓存1秒,1秒内直接返回上次成功请求的结果。
            utf8Client.configCurrentHttpCacheExpiry(1000);
            utf8Client.configResponseTextCharset("UTF-8");
            ResponseStream stream = utf8Client.sendSync(HttpMethod.GET, "http://api.map.baidu.com/telematics/v3/weather", params);
            String content = stream.readString();
            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(content).get("results").get(0);
                //pm25 = jsonNode.get("pm25").textValue();
                temperature = jsonNode.get("weather_data").get(0).get("temperature").textValue();

                mHandler.sendEmptyMessage(0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

效果图:
这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ithouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值