Android 使用GPRS获取手机地理位置 以及 Location 获取为空的解决办法

最近想做一个程序,需要用到获取手机的地理位置,网上一搜一摞一摞的,但基本方法还是一样的。于是,找了一个比较工整的,看了下程序的逻辑,便直接用了。但是发现location每次都获取为null, 最后改完之后代码如下:

1.AndroidManifest.xml 文件中加入以下许可:

1     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
2     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

2.程序界面 main.xml 文件代码:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7     <Button android:id="@+id/query"
 8         android:text="查询所在城市"
 9         android:layout_width="fill_parent" android:layout_height="wrap_content"/>
10     <TextView android:id="@+id/cityString" 
11         android:layout_width="fill_parent" android:layout_height="wrap_content" 
12     />
13 </LinearLayout>

3. MainActivity.java 代码:

 1 public class MainActivity extends Activity {
 2     
 3     Button queryButton;
 4     TextView cityString;
 5     
 6     
 7     /** Called when the activity is first created. */
 8     @Override
 9     public void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.main);
12         
13         queryButton = (Button)findViewById(R.id.query);
14         cityString = (TextView)findViewById(R.id.cityString);
15         
16         queryButton.setOnClickListener(new OnClickListener() {
17             
18             @Override
19             public void onClick(View v) {
20                 LocationManager locationManager;
21                 String serviceName = Context.LOCATION_SERVICE;
22                 locationManager = (LocationManager) getSystemService(serviceName);
23                 // String provider = LocationManager.GPS_PROVIDER;
24                 Criteria criteria = new Criteria();
25                 criteria.setAccuracy(Criteria.ACCURACY_FINE);
26                 criteria.setAltitudeRequired(false);
27                 criteria.setBearingRequired(false);
28                 criteria.setCostAllowed(true);
29                 criteria.setPowerRequirement(Criteria.POWER_LOW);
30                 String provider = locationManager.getBestProvider(criteria, true);
31                 locationManager.requestLocationUpdates(provider, 2000, 10,
32                         locationListener);
33                 Location location = locationManager.getLastKnownLocation(provider);
34                 while (location == null) {
35                     location = locationManager.getLastKnownLocation(provider);
36                 }
37                 updateWithNewLocation(location);
38                 locationManager.removeUpdates(locationListener);
39             }
40         });    
41     }
42 
43     private final LocationListener locationListener = new LocationListener() {
44         public void onLocationChanged(Location location) {
45             updateWithNewLocation(location);
46         }
47 
48         public void onProviderDisabled(String provider) {
49             updateWithNewLocation(null);
50         }
51 
52         public void onProviderEnabled(String provider) {
53         }
54 
55         public void onStatusChanged(String provider, int status, Bundle extras) {
56         }
57     };
58 
59     private void updateWithNewLocation(Location location) {
60         String latLongString;
61         TextView myLocationText;
62         myLocationText = (TextView) findViewById(R.id.cityString);
63         if (location != null) {
64             double lat = location.getLatitude();
65             double lng = location.getLongitude();
66             latLongString = "纬度:" + lat + "\n经度:" + lng + "\n";
67             
68             Geocoder gc = new Geocoder(MainActivity.this, Locale.getDefault());
69             try { 
70                 // 取得地址相关的一些信息\经度、纬度 
71                 List<Address> addresses = gc.getFromLocation(lat, lng, 1); 
72                 StringBuilder sb = new StringBuilder(); 
73                 if (addresses.size() > 0) { 
74                     Address address = addresses.get(0); 
75                     sb.append(address.getLocality()).append("\n"); 
76                     latLongString = latLongString + sb.toString(); 
77                 } 
78             } catch (IOException e) { 
79             } 
80 
81         } else {
82             latLongString = "无法获取地理信息";
83         }
84         myLocationText.setText("您当前的位置是:\n" + latLongString);
85     }    
86 }

之前看的网上的代码,没有34~36行,结果获取出来location值为null,现在的代码通过手机位置移动事件给location赋值,再加上这三行之后就可以了。后来看见《Android开发入门教程》里有一句话:
“getLastKnownPosition() 返回近期所处的位置,但“近期”也许已经过期(例如,电话关掉)或者甚至是 null (如果没有为程序提供位置记录)”。

所以,后来想也许调用两次这个函数就可以,不必使用while循环。不过没有测试,如果哪位高人觉得程序有问题请多指教。

原文地址:https://www.cnblogs.com/lihuiyy/p/2725407.html