代码如下:
package com.example.x.first;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
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.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by X on 2016/8/10.
*/
public class MyWeather extends Activity {
private static final int UpdateCity = 0;
private static final int updateWeather = 1;
LocationManager locationManager;
Location location;
TextView tv_city;
TextView tv_type;
TextView tv_high;
TextView tv_low;
String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
initView();
initDate();
}
private void initView() {
tv_city = (TextView) findViewById(R.id.tv_city);
tv_type = (TextView) findViewById(R.id.tv_type);
tv_high = (TextView) findViewById(R.id.tv_high);
tv_low = (TextView) findViewById(R.id.tv_low);
findViewById(R.id.ibReturn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void initDate() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
setListener();
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UpdateCity:
tv_city.setText(address);
new MyThread().start();
break;
case updateWeather:
tv_high.setText(list.get(2).toString());
tv_low.setText(list.get(3).toString());
tv_type.setText(list.get(4).toString());
break;
}
}
};
public void setListener() {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// updateLocation(location);
try {
address = getCitynameByLocation(location);
handler.sendEmptyMessage(UpdateCity);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
if (ActivityCompat.checkSelfPermission(MyWeather.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyWeather.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
address = getCitynameByLocation(locationManager.getLastKnownLocation(provider));
handler.sendEmptyMessage(UpdateCity);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onProviderDisabled(String provider) {
// updateLocation(null);
try {
address = getCitynameByLocation(null);
handler.sendEmptyMessage(UpdateCity);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String getCitynameByLocation(Location location) throws IOException {
String latLongString = "";
String citiName = "";
// TextView myLocationText;
// myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// latLongString = "纬度:" + lat + "\n经度:" + lng;
List<Address> addList = null;
Geocoder ge = new Geocoder(this);
try {
addList = ge.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if(addList!=null && addList.size()>0){
for(int i=0; i<addList.size(); i++){
Address ad = addList.get(i);
// latLongString += "\n";
latLongString = ad.getCountryName() + ";" + ad.getLocality();
citiName = ad.getLocality();
}
}
} else {
latLongString = "无法获取地理信息";
}
System.out.println("您当前的位置是:\n" +latLongString);
// myLocationText.setText("您当前的位置是:\n" +latLongString);
return citiName;
}
public void checkGPSIsOpen(){
//判断GPS是否正常启动
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
//返回开启GPS导航设置界面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,0);
return;
}
}
//网络资源先获取输入流
public InputStream getIS(String path) {
InputStream is = null;
try {
//创建URL对象
URL url = new URL(path);
//获得httpurlconnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方法
conn.setRequestMethod("GET");
//获取输入流
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// String path = "http://wthrcdn.etouch.cn/WeatherApi?city=%E5%8D%97%E4%BA%AC";
String path = "http://wthrcdn.etouch.cn/WeatherApi?city=";
String city;
String cityPath;
List list;
public class MyThread extends Thread {
@Override
public void run() {
try{
int index = address.indexOf("市");
if (index!=-1){
city = URLEncoder.encode(address.substring(0,index),"UTF-8");
}else {
city = URLEncoder.encode(address,"UTF-8");
}
cityPath = path + city;
System.out.println("cityPath---->"+cityPath);
InputStream is = getIS(cityPath);
// String str = convertStreamToString(is);
list = xmlParse(is);
handler.sendEmptyMessage(updateWeather);
}catch (Exception e){
e.printStackTrace();
}
}
}
public List xmlParse(InputStream is) {
List alist = new ArrayList();
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// Document document = builder.parse(getAssets().open("weather.xml")) ;
Document document = builder.parse(is);
Element root = document.getDocumentElement();
//获取城市
NodeList list = root.getElementsByTagName("city");
String city = list.item(0).getTextContent();
NodeList list_wendu = root.getElementsByTagName("wendu");
String wendu = list_wendu.item(0).getTextContent();
System.out.println("city----------------->" + city);
//获取当天信息
NodeList list1 = root.getElementsByTagName("forecast");
Element list_forecast = (Element) list1.item(0);
Element element_weather = (Element) list_forecast.getElementsByTagName("weather").item(0);
String weather_high = element_weather.getElementsByTagName("high").item(0).getTextContent();
System.out.println("weather_high----------------->" + weather_high);
String weather_low = element_weather.getElementsByTagName("low").item(0).getTextContent();
System.out.println("weather_low----------------->" + weather_low);
Element day = (Element) element_weather.getElementsByTagName("day").item(0);
String type = day.getElementsByTagName("type").item(0).getTextContent();
System.out.println("type----------------->" + type);
alist.add(city);
alist.add(wendu);
alist.add(weather_high);
alist.add(weather_low);
alist.add(type);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return alist;
}
}
权限:
<uses-permission android:name="android.permission.INTERNET" />