首先需要在模拟器中手動添加GPS資訊,有兩種手動添加方法
1、在eclipse下,windows-->open perspective-->DDMS-->Emulator control-->Manual下手動設定經緯度,并按send按鈕。
2、在cmd下手動添加資訊。
(1)首先打開模拟器,然後運作cmd,輸入telnet localhost 5554(注:5554是模拟器在本機的端口,有可能不一樣哈,具體端口号,模拟器左上方有顯示的),這樣會出現
Android Console: type 'help' for a list of commands
OK的字樣。
如果是使用WIN7的朋友,控制台可能會提示telnet無效什麼的,那是因為WIN7下預設是不出現telnet的,需要手動打開。具體為:[1]控制台-->程式-->打開或關閉Windows功能,然後将Telnet伺服器和Telnet用戶端勾選上。[2]然後在管理工具-->服務中手動啟動Telnet
(2)使用geo指令模拟發送GPS信号:
geo fix 經度 緯度
(3)這時就會發現在模拟器的狀态欄上多了一個GPS的标志.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class TT extends Activity {
TextView myLocationText;
TextView myLongitude;
TextView myLatitude;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String serviceName=Context.LOCATION_SERVICE;
locationManager=(LocationManager)this.getSystemService(serviceName);
//查詢條件
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider=locationManager.getBestProvider(criteria,true);
Location location=locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
//設定監聽器,自動更新的最小時間為間隔1秒,最小位移變化超過5米
locationManager.requestLocationUpdates(provider, 1000, 5, locationListener);
}
private final LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location) {
updateWithNewLocation(location);}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private void updateWithNewLocation(Location location){
myLocationText = (TextView)this.findViewById(R.id.myLocationText);
myLongitude = (TextView)this.findViewById(R.id.myLongitude);
myLatitude = (TextView)this.findViewById(R.id.myLatitude);
if(location!=null){
myLongitude.setText(String.valueOf(location.getLongitude()));
myLatitude.setText(String.valueOf(location.getLatitude()));
}else{
myLongitude.setText("No GPS");
}
myLocationText.setText("您所在位置為:");
}
}
xml檔案中加一個權限 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />