[java]
<span style="background-color: rgb(243, 248, 251); font-family: simsun;">用戶定位介紹:</span>
User Location的作用:
1.獲取用戶的位置
2.追蹤用戶的移動
User Location的關鍵API
1.Location Manager:用於管理Android的用戶定位服務
2.Location Providers:提供多種定位方式供開發者選擇。
<1>GPS Provider
<2>Network Provider
<3>Passive
定位方式的分類:
1.GPS定位:使用GPS衛星進行定位,需要在AndroidManifest.xml當中聲明如下權限:
android.permission.ACCESS_FINE_LOCATION
2.NETWORK定位:使用信號接收塔和WIFI接入點進行定位,需要在AndroidManifest.xml當中聲明如下權限:
android.permission.ACCESS_FINE_LOCATION
或
android.permission.ACCESS_COARSE_LOCATION
以上兩種定位方式的區別是GPS定位精度更高,但同時也更耗電
獲取用戶的當前位置:
1.在AndroidManifest.xml當中聲明相應的權限;
2.獲取LocationManager對象;
3.選擇LocationProvider;
4.綁定LocationListener對象。
LocationListener有四個方法:
1.onLocationChanged(Location location):當設備的位置發生改變時調用
我們可以調用location.getLongitude()和location.getLatitude()來得到設備所處的經度和緯度
2.onProviderDisabled(String provider):當提供數據Provider禁用時調用
3.onProviderEnabled(String provider):當提供數據的Provider使用時調用
4.onStatusChanged(String provider,int status,Bundle extras):當狀態改變時
我們需要實現LocationListener的以上四個方法:
[java]
<span style="font-size:18px;">private class TestLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location){
System.out.println(location.getLongitude());
System.out.println(location.getLatitude());
}
@Override
public void onProviderDisabled(String provider){
// do something you need
}
@Override
public void onProviderEnabled(String provider){
// do something you need
}
@Override
public void onStatusChanged(String provider,int status,Bundle extras){
// do something you need
}
}</span>
測試當前設備的LocationProvider
由於一般的設備存在不止一種定位方法,所以在這裡給出查找定位服務的方法:
[java]
<span style="font-size:18px;">List<String> providers=locationManager.getAllProviders();
for(Iterator<String> iterator=providers.iterator();iterator.hasNext();){
String string=(String)iterator.next();
Log.d("BruceZhang", string+"\n");</span>
由於有多個Provider,那麼就需要做出選擇,在這裡給出選擇最好的Provider的方法:
此時需要用到一個類--Criteria
下面是在Android SDK文檔上給出的解釋:
A class indicating the application criteria for selecting a location provider. Providers maybe ordered according to accuracy, power usage, ability to report altitude, speed, and bearing, and monetary cost.
它提供了一系列的方法,設置用戶的需求,並最終給出用戶所需要的最佳的Provider,下面是文檔上對設置條件的解釋:
[java] view plaincopy
<span style="font-size:18px;">void setAccuracy(int accuracy)
Indicates the desired accuracy for latitude and longitude.</span>
[java]
<span style="font-size:18px;">
void setAltitudeRequired(boolean altitudeRequired)
Indicates whether the provider must provide altitude information.</span>
[java]
<span style="font-size:18px;">
void setBearingAccuracy(int accuracy)
Indicates the desired bearing accuracy.</span>
[java
<span style="font-size:18px;">
void setBearingRequired(boolean bearingRequired)
Indicates whether the provider must provide bearing information.</span>
[java]
<span style="font-size:18px;">
void setCostAllowed(boolean costAllowed)
Indicates whether the provider is allowed to incur monetary cost.</span>
[java]
<span style="font-size:18px;">
void setHorizontalAccuracy(int accuracy)
Indicates the desired horizontal accuracy (latitude and longitude).</span>
[java]
<span style="font-size:18px;">
void setPowerRequirement(int level)
Indicates the desired maximum power level.</span>
[java]
<span style="font-size:18px;">
void setSpeedAccuracy(int accuracy)
Indicates the desired speed accuracy.</span>
[java] view plaincopy
<span style="font-size:18px;">
void setSpeedRequired(boolean speedRequired)
Indicates whether the provider must provide speed information.</span>
[java] view plaincopy
<span style="font-size:18px;">
void setVerticalAccuracy(int accuracy)
Indicates the desired vertical accuracy (altitude).</span>
追蹤用戶的位置:
對用戶的位置進行更新用到的方法和解釋如下:
[java]
// public void requestLocationUpdates (String provider,
// long minTime, float minDistance, LocationListener listener)
// Added in API level 1
// Register for location updates using the named provider, and a pending intent.
//
// Parameters
// provider the name of the provider with which to register
// minTime minimum time interval between location updates, in milliseconds
// minDistance minimum distance between location updates, in meters
// listener a LocationListener whose onLocationChanged(Location) method will be called for each location update
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new TestLocationListener());
下面,給出一個例子,實現用戶的定位,取得支持的LocationProvider,根據條件獲取最佳的Provider:
一下是實現的源代碼:
[java]
public class MainActivity extends Activity {
private Button button;
private Button button2;
private Button button3;
private Button button4;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button.setOnClickListener(new ButtonListener());
button2.setOnClickListener(new ProviderButtonListener());
button3.setOnClickListener(new BestProviderButtonListener());
button4.setOnClickListener(new MyLocation());
locationManager=(LocationManager)MainActivity.this.
getSystemService(Context.LOCATION_SERVICE);
}
private class ButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// LocationManager locationManager=(LocationManager)MainActivity.this.
// getSystemService(Context.LOCATION_SERVICE);
/*
* 各個參數的意義:
* 1.定義當前所使用的Location Provider
* 2.位置更新一次的最小時間間隔
* 3.位置更新的最小距離
* 4.綁定監聽器--位置發生變化會調用其中的方法
*/
Log.d("BruceZhang", "Bond Success");
// public void requestLocationUpdates (String provider,
// long minTime, float minDistance, LocationListener listener)
// Added in API level 1
// Register for location updates using the named provider, and a pending intent.
//
// Parameters
// provider the name of the provider with which to register
// minTime minimum time interval between location updates, in milliseconds
// minDistance minimum distance between location updates, in meters
// listener a LocationListener whose onLocationChanged(Location) method will be called for each location update
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new TestLocationListener());
}
}
private class ProviderButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<String> providers=locationManager.getAllProviders();
for(Iterator<String> iterator=providers.iterator();iterator.hasNext();){
String string=(String)iterator.next();
Log.d("BruceZhang", string+"\n");
}
}
}
private class BestProviderButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(false);
//第二個參數設置為false時,不管當前的那個provider是否可用,都需要進行查找,並根據條件設為最優
String provider=locationManager.getBestProvider(criteria, false);
Log.d("BruceZhang", "The best provider is:"+provider);
}
}
private class MyLocation implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//對用用戶定位服務主要是中間兩個參數的設置
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
2000, new TestLocationListener());
}
}
private class TestLocationListener implements LocationListener{
//這個函數的參數是用戶當前的位置
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
// Toast.makeText(MainActivity.this, "您當前的經度是:"+arg0.getLongitude()+" ,"+
// "您當前的緯度是:"+arg0.getLatitude(),
// Toast.LENGTH_SHORT).show();
Log.d("BruceZhang", arg0.getLongitude()+"");
Log.d("BruceZhang", arg0.getLatitude()+"");
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override www.2cto.com
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}