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循環。不過沒有測試,如果哪位高人覺得程序有問題請多指教。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM