Android調用系統功能獲取當前經緯度

package com.example.locationtest;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private TextView positionTextView;//用來顯示當前位置信息
    private LocationManager locationmanager;//位置管理器
    private String provider;//用GPS還是網絡來定位

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        positionTextView = (TextView) findViewById(R.id.position_text_view);
        locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        List<String> providerList = locationmanager.getProviders(true);
        if(providerList.contains(LocationManager.GPS_PROVIDER)){
            provider = LocationManager.GPS_PROVIDER;
            //如果是用GPS來定位
        }
        else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
            provider = LocationManager.NETWORK_PROVIDER;
            //如果是用網絡來定位
        }
        else{
            Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
            //無可用定位工具
            return;
        }
        Location location = locationmanager.getLastKnownLocation(provider);
        //得到最近位置
        if(location!=null){
            showLocation(location);//位置存在則顯示位置
        }
        locationmanager.requestLocationUpdates(provider, 5000, 10, locationListener);//位置更新器,偵聽每5S/10M的位置改變
    }

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if(locationmanager!=null){
        locationmanager.removeUpdates(locationListener);
    }
}

LocationListener locationListener = new LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        showLocation(location);

    }
};
    private void showLocation(Location location){
        String currentPosition = "latitude is"+location.getLatitude()+"\n"//經度
                +"longitude is"+location.getLongitude()+"\n"+//緯度
                 "altitude is" + location.getAltitude()//海拔
                ;
        positionTextView.setText(currentPosition);
    }
}
發佈了58 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章