定位实现代码:

<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>

最新文章

  1. webform 组合查询
  2. react-native环境搭建
  3. Mathematics:X-factor Chains(POJ 3421)
  4. sqoop的增量导入(increment import)
  5. WPF WebBrowser屏蔽弹出alert ,confirm ,prompt ,showModalDialog() ,window.open()
  6. 【数论+技巧】神奇的Noip模拟试题第二试 T1 素数统计
  7. IOS 日期选择
  8. python全栈开发-Day8 函数基础
  9. Hadoop2.0伪分布式平台环境搭建
  10. 搭建Eureka注册中心
  11. 20172325 2018-2019-2 《Java程序设计》第八周学习总结
  12. vue开发小结(上)
  13. php-fpm开机自动启动脚本其实源码包里边就有
  14. MyBatis基础入门《六》Like模糊查询
  15. Hadoop学习笔记之五:HDFS功能逻辑(1)
  16. linux文件和目录的删除、新建、移动等操作
  17. C++指针一
  18. No.14 selenium for python table表单
  19. 【转】Java Spring AOP详解
  20. 20190313-时间和日期-Time

热门文章

  1. GRU-CTC中文语音识别
  2. 150命令之线上查询及帮助命令 man hellp
  3. 20145214《Java程序设计》课程总结
  4. asp.net .net4.0使用异步编程
  5. Alpha-5
  6. ACM 第十六天
  7. 利用JavaScriptSerializer类 进行Json对象的序列化和反序列化和过滤
  8. QT分析之调试跟踪系统
  9. Tomcat启动报错ERROR:transport error 202:bind failed:Address already
  10. ueditor 定制工具栏图标