您的位置:首页 > 移动开发 > Android开发

安卓基于位置的服务学习整理

2015-11-13 13:16 411 查看
借助LocationManager类实现定位

在AndroidMainfest.xml声明权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

//实例化LocationManager

locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

//获取可用的位置提供器

List<String> providerList=locationManager.getProviders(true);

        if(providerList.contains(LocationManager.GPS_PROVIDER)){

            provider=LocationManager.GPS_PROVIDER;

        }else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){

            provider=LocationManager.NETWORK_PROVIDER;

            

        }else{

            Toast.makeText(this, "没有可用的定位",Toast.LENGTH_SHORT).show();

            return;

        }

//获取当前位置信息

location=locationManager.getLastKnownLocation(provider);

//显示位置

        if(location!=null){

            showLocation(location);

            

        }

//更新位置信息

locationManager.requestLocationUpdates(provider,5000, 1, locationListener);

//位置监听器      

LocationListener locationListener=new LocationListener() {

        

        

        @Override

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

            // TODO Auto-generated method stub

            

        }

        

        @Override

        public void onProviderEnabled(String arg0) {

            // TODO Auto-generated method stub

            

        }

        

        @Override

        public void onProviderDisabled(String arg0) {

            // TODO Auto-generated method stub

            

        }

        

        @Override

        public void onLocationChanged(Location arg0) {

            // TODO Auto-generated method stub

            showLocation(location);

        }

    };

//显示位置的实现

    private void showLocation(Location location){

        String currentLocation="纬度是"+location.getLatitude()+"\n"+"经度是"+location.getLongitude();

        positionTextView.setText(currentLocation);

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android学习