定位实现代码:

<span style="font-size:14px;">import java.io.IOException;
import java.util.List; import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle; public class LocationUtils {
public static String cityName; //城市名
private static Geocoder geocoder; //此对象能通过经纬度来获取相应的城市等信息
//通过地理坐标获取城市名 其中CN分别是city和name的首字母缩写
public static void getCNBylocation(Context context){
geocoder = new Geocoder(context);
//用于获取Location对象,以及其他
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
//实例化一个LocationManager对象
locationManager = (LocationManager) context.getSystemService(serviceName);
//provider的类型
String provider = LocationManager.NETWORK_PROVIDER; Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW); //低精度 高精度:ACCURACY_FINE
criteria.setAltitudeRequired(false); //不要求海拔
criteria.setBearingRequired(false); //不要求方位
criteria.setCostAllowed(false); //不允许产生资费
criteria.setPowerRequirement(Criteria.POWER_LOW); //低功耗 //通过最后一次的地理位置来获取Location对象
Location location = locationManager.getLastKnownLocation(provider); String queryed_name = updateWithNewLocation(location);
if((queryed_name!=null)&&(0!=queryed_name.length())){
cityName = queryed_name;
}
/*
第二个参数表示更新的周期,单位为毫秒,
第三个参数的含义表示最小距离间隔,单位是米,设定每30秒进行一次自动定位
*/
locationManager.requestLocationUpdates(provider, 30000, 50, locationListener);
//移除监听器,在只有一个widget的时候,这个还是适用的
locationManager.removeUpdates(locationListener);
}
//方位改变是触发,进行调用
private final static LocationListener locationListener = new LocationListener() {
String tempCityName;
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
tempCityName = updateWithNewLocation(null);
if((tempCityName!=null)&&(tempCityName.length()!=0)){
cityName = tempCityName;
}
}
@Override
public void onLocationChanged(Location location) {
tempCityName = updateWithNewLocation(location);
if((tempCityName!=null)&&(tempCityName.length()!=0)){
cityName = tempCityName;
}
}
};
//更新location return cityName
private static String updateWithNewLocation(Location location){
String mcityName = "";
double lat = 0;
double lng = 0;
List<Address> addList = null;
if(location!=null){
lat = location.getLatitude();
lng = location.getLongitude();
}else{
cityName = "无法获取地理信息";
}
try {
addList = geocoder.getFromLocation(lat, lng, 1); //解析经纬度
} catch (IOException e) {
e.printStackTrace();
}
if(addList!=null&&addList.size()>0){
for(int i=0;i<addList.size();i++){
Address add = addList.get(i);
mcityName += add.getLocality();
}
}
if(mcityName.length()!=0){
return mcityName.substring(0, (mcityName.length()-1));
}else{
return mcityName;
}
}
}
</span>
<span style="font-size:14px;">public class TargetUrl {
public final static String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=";
public final static String url2 = "&output=json&ak=9cCAXQFB468dsH11GOWL8Lx4";
}
</span>

根据定位到的城市名获取天气信息实现代码:

<span style="font-size:14px;">import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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 org.json.JSONArray;
import org.json.JSONObject; import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import com.mine.xinlangapp.R;
import com.mine.xinlangapp.activity.MainActivity;
import com.mine.xinlangapp.location.LocationUtils;
import com.mine.xinlangapp.location.TargetUrl; public class TupianFragment extends Fragment{
private TextView tv, tv1, tv2, tv3, tv4, tv5;
private ImageView iv_one, iv_two;
private static String cityName = "";
private String result = "";
private static Context context = null;
private Bitmap bitmap1, bitmap2;
private static TupianFragment tupian = null;
public static int tupian_hour = 60;
private static Handler handler3 = new Handler();
@SuppressWarnings("deprecation")
private static Runnable runnable = new Runnable() {
@Override
public void run() {
tupian.getActivity().removeDialog(0);
Toast.makeText(tupian.getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
// handler3.postDelayed(this, 2000); //每两秒执行一次runnable
}
};
//自动刷新
private Runnable runnable2 = new Runnable() {
@Override
public void run() {
tupian.send(cityName);
Message m = tupian.handler.obtainMessage();
tupian.handler.sendMessage(m);
handler3.postDelayed(this, tupian_hour*3600*1000);
}
};
@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public static Handler handler1 = new Handler(){
public void handleMessage(Message msg){
tupian.getActivity().showDialog(0);
//启动定时器
handler3.postDelayed(runnable, 5000); //五秒后执行
new Thread(new Runnable() {
@Override
public void run() {
tupian.send(cityName);
Message m = tupian.handler.obtainMessage();
tupian.handler.sendMessage(m);
}
}).start();
}
};
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
public void handleMessage(Message msg){
if(result != null){
try {
JSONObject datajson = new JSONObject(result); //第一步,将String格式转换回json格式
JSONArray results = datajson.getJSONArray("results"); //获取results数组 JSONObject city = results.getJSONObject(0);
String currentCity = city.getString("currentCity"); //获取city名字
String pm25 = city.getString("pm25"); //获取pm25
tv.setText("城市:"+currentCity+"\n"+"pm25:"+pm25); //测试城市和pm25
JSONArray index = city.getJSONArray("index"); //获取index里面的JSONArray
//获取穿衣
JSONObject cy = index.getJSONObject(0);
String titlec = cy.getString("title");
String zsc = cy.getString("zs");
String tiptc = cy.getString("tipt");
String desc = cy.getString("des");
//获取洗车
JSONObject xc = index.getJSONObject(1);
String titlex = xc.getString("title");
String zsx = xc.getString("zs");
String tiptx = xc.getString("tipt");
String desx = xc.getString("des");
tv1.setText(titlec+" : "+zsc+"\n"+tiptc+" : "+desc);
tv2.setText(titlex+" : "+zsx+"\n"+tiptx+" : "+desx); //weather_data, 未来几天
JSONArray weather_data = city.getJSONArray("weather_data");
//获取今天
JSONObject today = weather_data.getJSONObject(0);
String date0 = today.getString("date");
final String dayPictureUrl0 = today.getString("dayPictureUrl");
final String nightPictureUrl0 = today.getString("nightPictureUrl");
String weather0 = today.getString("weather");
String wind0 = today.getString("wind");
String temperature0 = today.getString("temperature");
tv3.setText("\n"+"今天:"+date0+"\n"+"实时:"+weather0+"\n"+"风力:"+
wind0+"\n"+"温度范围:"+temperature0+"\n"); //获取明天
JSONObject tomorrow = weather_data.getJSONObject(1);
String date1 = tomorrow.getString("date");
String weather1 = tomorrow.getString("weather");
String wind1 = tomorrow.getString("wind");
String temperature1 = tomorrow.getString("temperature");
tv4.setText("明天:"+date1+"\n"+weather1+"\n"+
"风力:"+wind1+"\n"+"温度范围:"+temperature1+"\n"); //获取后天
JSONObject after_tomorrow = weather_data.getJSONObject(2);
String date2 = after_tomorrow.getString("date");
String weather2 = after_tomorrow.getString("weather");
String wind2 = after_tomorrow.getString("wind");
String temperature2 = after_tomorrow.getString("temperature");
tv5.setText("后天:"+date2+"\n"+weather2+"\n"+
"风力:"+wind2+"\n"+"温度范围:"+temperature2+"\n"); new Thread(new Runnable() {
@Override
public void run() {
bitmap1 = returnBitMap(dayPictureUrl0);
bitmap2 = returnBitMap(nightPictureUrl0);
Message m = handler2.obtainMessage();
handler2.sendMessage(m);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
super.handleMessage(msg);
}
};
@SuppressWarnings("deprecation")
@SuppressLint("HandlerLeak")
private Handler handler2 = new Handler(){
public void handleMessage(Message msg){
if(bitmap1!=null)
iv_one.setImageBitmap(bitmap1);
if(bitmap2!=null)
iv_two.setImageBitmap(bitmap2);
if(bitmap1!=null&&bitmap2!=null){
//停止计时器
handler3.removeCallbacks(runnable);
tupian.getActivity().removeDialog(0);
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
context = TupianFragment.this.getActivity();
tupian = TupianFragment.this;
LocationUtils.getCNBylocation(context);
cityName = LocationUtils.cityName;
MainActivity.text.setText(cityName); View view = inflater.inflate(R.layout.tupianfragment, container,false);
iv_one = (ImageView) view.findViewById(R.id.iv_one);
iv_two = (ImageView) view.findViewById(R.id.iv_two);
tv = (TextView) view.findViewById(R.id.tv);
tv1 = (TextView) view.findViewById(R.id.tv1);
tv2 = (TextView) view.findViewById(R.id.tv2);
tv3 = (TextView) view.findViewById(R.id.tv3);
tv4 = (TextView) view.findViewById(R.id.tv4);
tv5 = (TextView) view.findViewById(R.id.tv5);
//启动计时器
handler3.postDelayed(runnable2, tupian_hour*3600*1000); new Thread(new Runnable() {
@Override
public void run() {
send(cityName);
Message m = handler.obtainMessage();
handler.sendMessage(m);
}
}).start(); return view;
}
private String send(String city){
String target = TargetUrl.url1+city+TargetUrl.url2; //要提交的目标地址
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(target); //创建HttpGet对象
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
result = EntityUtils.toString(httpResponse.getEntity()).trim(); //获取返回的字符串
}else{
result = "fail";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
//以Bitmap的方式获取一张图片
public Bitmap returnBitMap(String url){
URL myFileUrl = null;
Bitmap bitmap = null;
try{
myFileUrl = new URL(url);
}catch(MalformedURLException e){
e.printStackTrace();
}
try{
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}catch(IOException e){
e.printStackTrace();
}
return bitmap;
}
@Override
public void onDestroy() {
//停止计时器
handler3.removeCallbacks(runnable2);
super.onDestroy();
}
}
</span>

最后别忘记添加权限:

<span style="font-size:14px;">    <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></span>

说明:

<span style="font-size:14px;">criteria.setAccuracy(Criteria.ACCURACY_LOW);    //低精度   高精度:ACCURACY_FINE
使用网络定位要选择低精度,如果选择了高精度它会第一选择为:GPS定位,没有开启GPS定位,才会使用网络定位。
</span>

Android实现自动定位城市并获取天气信息的更多相关文章

  1. C#调用WebService获取天气信息

    概述 本文使用C#开发Winform应用程序,通过调用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服务WeatherWS来获取天气预 ...

  2. java获取天气信息

    通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...

  3. Java通过webservice接口获取天气信息

    通过SOAP请求的方式获取天气信息并解析返回的XML文件. 参考: http://www.webxml.com.cn/WebServices/WeatherWS.asmx import java.io ...

  4. ajax无刷新获取天气信息

    浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据,但是可以再本地的服务器上获取其他服务器的信息,在通过ajax请求本地服务来实现: <?php header("conten ...

  5. ESP32 IDF 获取天气信息

    一.注册天气获取账号 我使用的知心天气,没有获取天气账号的小伙伴可以去注册一下,知心天气官网:https://www.seniverse.com/ 取得天气获取的API后,可以直接在浏览器中访问测试一 ...

  6. 半吊子学习Swift--天气预报程序-获取天气信息

    昨天申请的彩云天气Api开发者今天上午已审核通过  饭后运动过后就马不停蹄的来测试接口,接口是采用经纬度的方式来获取天气信息,接口地址如下 https://api.caiyunapp.com/v2/ ...

  7. 内网公告牌获取天气信息解决方案(C# WebForm)

    需求:内网公告牌能够正确显示未来三天的天气信息 本文关键字:C#/WebForm/Web定时任务/Ajax跨域 规划: 1.天定时读取百度接口获取天气信息并存储至Txt文档: 2.示牌开启时请求Web ...

  8. Kettle通过Webservice获取天气信息

      Kettle通过Webservice获取天气信息 需求: 通过kettle工具,通过webservice获取天气信息,写成xml格式文件. 思路: Kettle可通过两种选择获取webservic ...

  9. java解析xml实例——获取天气信息

    获取xml并解析其中的数据: package getweather.xml; import java.io.IOException; import java.util.HashMap; import ...

随机推荐

  1. day-16 CNN卷积神经网络算法之Max pooling池化操作学习

    利用CNN卷积神经网络进行训练时,进行完卷积运算,还需要接着进行Max pooling池化操作,目的是在尽量不丢失图像特征前期下,对图像进行downsampling. 首先看下max pooling的 ...

  2. 十:HDFS Short-Circuit Local Reads 短路本地读取

    当client请求数据时,datanode会读取数据然后通过TCP协议发送给client.short-circuit绕过了datanode直接读取数据.short-circuit的前提是client和 ...

  3. Keil ARM-CM3 printf输出调试信息到Debug (printf) Viewer

    参考资料:http://www.keil.com/support/man/docs/jlink/jlink_trace_itm_viewer.htm 1.Target Options -> De ...

  4. Thunder团队第五周 - Scrum会议5

    Scrum会议5 小组名称:Thunder 项目名称:i阅app Scrum Master:翟宇豪 工作照片: 杨梓瑞同学在拍照,所以不在照片内. 参会成员: 王航:http://www.cnblog ...

  5. 20172330 2017-2018-1 《Java程序设计》第五周学习总结

    20172330 2017-2018-1 <Java程序设计>第五周学习总结 教材学习内容总结 第五章 首先是对各种各种运算符的了解:刚开始以为相等就是=,还有其他一些符号都挺简单的,然后 ...

  6. 20145214实验四 Android开发基础

    20145214实验四 Android开发基础 实验内容及步骤 安装 JDK 并配置 JDK 环境变量 找到之前path变量中的jdk文件所在位置并复制. 用复制的变量名新建一个 JAVA_HOME ...

  7. Java 类和Static关键字

    类的定义 类的命名.首字母大写 大括号后面没有分号 成员变量 Java会自动初始化成员变量但是不会自动初始化局部变量: 可以在定义成员变量是直接初始化,成员变量的作用范围在整个类体 对象的创建和引用的 ...

  8. khan academy js

    Documentation Quick Jump: Shapes, Complex Shapes, Colors, Text, Transforms, Environment, Mouse, Keyb ...

  9. iOS- 显示数据列表最常用的一个控件UITableView

    相信做过iOS的程序员,最熟悉的控件一定少不了UITableView,最常用的控件也一定少不了UITableView! 今天分享一下自己对UITableView的实现大体思路,和整理出来的学习笔记! ...

  10. 【Linux】- 文件基本属性

    Linux系统是一种典型的多用户系统,不同的用户处于不同的地位,拥有不同的权限.为了保护系统的安全性,Linux系统对不同的用户访问同一文件(包括目录文件)的权限做了不同的规定. 在Linux中我们可 ...