android獲取位置數據

代碼:

package com.tc.gps;

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.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private LocationManager lm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateView(location);
        //每3秒更新一下
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {

            @Override//當GPS狀態改變時監聽
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override//GPS可用時監聽
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override//GPS不可用時監聽
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override//位置改變時監聽
            public void onLocationChanged(Location location) {
                updateView(location);
            }


        });



    }
    private void updateView(Location location) {
        double lng=location.getLongitude();//經度
        double lat=location.getLatitude();//緯度
        if (location!=null) {
            StringBuilder sb=new StringBuilder();
            sb.append("實時的位置信息:\n")
            .append("經度:")
            .append(location.getLongitude())
            .append("緯度:")
            .append(location.getLatitude())
            .append("高度")
            .append(location.getAltitude())
            .append("速度")
            .append(location.getSpeed())
            .append("方向")
            .append(location.getBearing());
            Toast.makeText(this, ""+sb.toString(), Toast.LENGTH_SHORT).show();
        }
    }

}

經緯度可集成高德地圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章