要用到jackson json相关jar包,请自行下载,我已经上传到csdn,免费,需要的可以下载:
还要用到xUtils相关jar包(可选,由于根据城市名获取天气的方法要用到几个参数和设定返回编码,我直接用xUtils来完成了。),我也上传到了csdn,免费,需要的可以下载:
清单文件:
<?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();
}
}
}
效果图:
321



被折叠的 条评论
为什么被折叠?



