Android入門之簡單GPS定位實例
添加權限:android.permission.ACCESS_FINE_LOCATION
- import android.app.Activity;
- import android.content.Context;
- import android.location.*;
- import android.os.*;
- import android.widget.*;
-
- public class GPSTest extends Activity {
-
- private LinearLayout mainView=null;
- private TextView infoView=null;
- private TextView locationView=null;
-
- private LocationManager locationManager=null;
- private LocationListener locationListener=null;
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mainView=new LinearLayout(this);
- mainView.setOrientation(LinearLayout.VERTICAL);
- infoView=new TextView(this);
- mainView.addView(infoView);
- locationView=new TextView(this);
- mainView.addView(locationView);
- setContentView(mainView);
- locationManager_init();
- }
- /*locationManager初始化*/
- void locationManager_init(){
- locationManager =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
- locationListener_init();
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0, locationListener);
- }
- /*locatonListener初始化*/
- void locationListener_init(){
- locationListener=new LocationListener(){
- //位置變化時觸發
- public void onLocationChanged(Location location) {
- locationView.setText("時間:"+location.getTime()+"\n");
- locationView.append("經度:"+location.getLongitude()+"\n");
- locationView.append("緯度:"+location.getLatitude()+"\n");
- locationView.append("海拔:"+location.getAltitude()+"\n");
- }
- //gps禁用時觸發
- public void onProviderDisabled(String provider) {
- infoView.setText("當前GPS狀態:禁用\n");
- }
- //gps開啟時觸發
- public void onProviderEnabled(String provider) {
- infoView.setText("當前GPS狀態:開啟\n");
- }
- //gps狀態變化時觸發
- public void onStatusChanged(String provider, int status,Bundle extras) {
- if(status==LocationProvider.AVAILABLE){
- infoView.setText("當前GPS狀態:可見的\n");
- }else if(status==LocationProvider.OUT_OF_SERVICE){
- infoView.setText("當前GPS狀態:服務區外\n");
- }else if(status==LocationProvider.TEMPORARILY_UNAVAILABLE){
- infoView.setText("當前GPS狀態:暫停服務\n");
- }
- }
- };
- }
- }