android 根据IP获取天气情况 详细讲解
分析:
此功能必须在可用的网络下运行的,确保在有可用网络下才能正常运行,获取当前网络IP判断所在城市,通过城市查询天气
1、首先判断网络是否正常(笔者做的是平板应用的一个模块有手机有些功能不一样)
[java]
public void getLocalIPAddress() {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!wm.isWifiEnabled()) {
Toast.makeText(this, "没有可用的网络", Toast.LENGTH_LONG).show();
}
}
2、其次要自动获取IP地址(webservice借口、相关网址),在此,笔者是根据网址获取,在进行解析
getCityIP()
[java]
public void getCityIP() {
URL url;
URLConnection conn = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
String str = "";
org.jsoup.nodes.Document doc;
try {
url = new URL("http://city.ip138.com/city.asp");
conn = url.openConnection();
is = conn.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String input = "";
while ((input = br.readLine()) != null) {
str += input;
}
doc = Jsoup.parse(str);
String ip1 = doc.body().text();
int start = ip1.indexOf("[");
int end = ip1.indexOf("]");
setIp(ip1.substring(start + 1, end));
} catch (Exception e) {
e.printStackTrace();
}
}
3、再次根据IP地址获取城市(webservice借口、解析网页)
getCityByIp():
[java]
public void getCityByIp() {
try {
URL url = new URL("http://whois.pconline.com.cn/ip.jsp?ip=" + getIp());
HttpURLConnection connect = (HttpURLConnection) url
.openConnection();
InputStream is = connect.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buff = new byte[256];
int rc = 0;
while ((rc = is.read(buff, 0, 256)) > 0) {
outStream.write(buff, 0, rc);
}
System.out.println(outStream);
byte[] b = outStream.toByteArray();
// 关闭
outStream.close();
is.close();
connect.disconnect();
String address = new String(b,"GBK");
if (address.startsWith("北")||address.startsWith("上")||address.startsWith("重")){
setCity(address.substring(0,address.indexOf("市")));
}
if(address.startsWith("香")){
setCity(address.substring(0,address.indexOf("港")));
}
if(address.startsWith("澳")){
setCity(address.substring(0,address.indexOf("门")));
}
if (address.indexOf("省") != -1) {
&nb
补充:移动开发 , Android ,