Android调用系统功能获取当前经纬度
16lz
2021-12-04
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 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的位置改变 }@Overrideprotected 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); }}
更多相关文章
- Android(安卓)GPS获取地理位置 .
- android应用程序的安装位置
- Android触屏测试实例代码
- android 修改AVD的存放位置
- Android中获取当前位置信息
- android 修改AVD的存放位置
- Android使用第三方SDK——百度地图
- Android帮助文档翻译——开发指南 获取用户位置
- 原创Android中应用界面布局总结