定位实现代码:

<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. opencv-学习笔记(6)图像梯度Sobel以及canny边缘检测

    opencv-学习笔记(6)图像梯度Sobel以及canny边缘检测 这章讲了 sobel算子 scharr算子 Laplacion拉普拉斯算子 图像深度问题 Canny检测 图像梯度 sobel算子 ...

  2. 六: Image Viewer 离线镜像查看器

    参考:http://hadoop.apache.org/docs/r2.6.3/hadoop-project-dist/hadoop-hdfs/HdfsImageViewer.html   离线镜像查 ...

  3. [git] Git in Practice

    Work flow with git and github Work with Remotes Check the current status git status Check the latest ...

  4. android仿系统Launcher界面,实现分屏,左右滑动效果(ViewSwitcher)

    ViewSwitcher代表了视图切换组件, 本身继承了FrameLayout ,可以将多个View叠在一起 ,每次只显示一个组件.当程序控制从一个View切换到另个View时,ViewSwitche ...

  5. 什么是BCL

    原文: 原文:https://www.cnblogs.com/1996V/p/9037603.html 什么是BCL 当你通过VS创建一个项目后,你这个项目就已经引用好了通过.NET下的语言编写好的一 ...

  6. com技术学习

    百度百科概念 COM是微软公司为了计算机工业的软件生产更加符合人类的行为方式开发的一种新的软件开发技术.在COM构架下,人们可以开发出各种各样的功能专一的组件,然后将它们按照需要组合起来,构成复杂的应 ...

  7. TCP系列34—窗口管理&流控—8、缓存自动调整

    一.概述 我们之前介绍过一种具有大的带宽时延乘积(band-delay product.BDP)的网络,这种网络称为长肥网络(LongFatNetwork,即LFN).我们想象一种简单的场景,假设发送 ...

  8. lol佐伊美图

      心血来潮,分享一波从各个网站上搜集到的佐伊美图,持续更新!(最近更新日期:2019/03/17) Section1 暮光星灵 2018/11/16 2019/02/15 2019/03/17 Se ...

  9. Linux less命令语法

    一.Linux less命令语法 less [参数] 文件 less命令非常强大,在此只介绍几个常用的参数,更多参数使用man less来查看Linux帮助手册. -b <缓冲区大小> 设 ...

  10. 【zoj2314】Reactor Cooling 有上下界可行流

    题目描述 The terrorist group leaded by a well known international terrorist Ben Bladen is buliding a nuc ...