对《第一行代码---Android》的学习笔记


基于位置的服务简介

基于位置服务简称LBS,主要工作原理就是利用无线电通讯网络GPs等定位方式确定移动位置的所在。

找到自己的位置

android使用LocationManager类实现

首先获取实例

LocationManager locationManager=(~)getSystemSeriver(Context.LOACTION_SERVICE);

然后需要选择一个位置提供器来确定设备的分当前位置。

Android提供了三种位置提供器可供选择:1.GPS——PROVIDER2.NETWORK_PROVIDER 3.PASSIVE_PROVIDER.

其中前两种使用的比较多,分别表示GPS定位和使用网络定位,前者定位的精准度比较高,但是非常耗电,而网络定位的精准度比较低,但耗电少。

将选择好的位置提供器传入到getLastKnownLocation()方法中,就可以得到一个Location对象

String provider=LocationManager.NETWORK_PROVIDER;  Location location=locationManager.getLastKnownLocation(provider);

这个Location对象中包含了经纬度,海拔等一系列的位置信息,然后从中提取我们需要的信息即可

如果有些时候你想让定位的精度更精确一点,但又不确定GPS定位的功能是否已经启用,这个时候就可以判断一下有哪些位置提供器

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

getProvides()方法接受一个布尔型参数,传入true就表示只有启用的位置提供器才会被返回,之后从providesList中判断是否包含GPS定位的功能就好。

使用requestLocationUpdates()方法,只要传入LocationListener的实例,就可以设备位置发生改变时获取最新的位置信息。

locationMabager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,new LocationListener(){});

参数:1.位置提供器的类型2.监听位置变化的时间间隔3.监听位置变化的距离间隔4.LocationListener监听器

反向地理编码,看的懂得位置信息

使用Geocoding API进行反向地理编码首先发送一个HTTP请求给谷歌服务器,然后将返回的JSON数据进行解析

public class MainActivity extends Activity {public static final int SHOW_LOCATION = 0;private TextView positionTextView;private LocationManager locationManager;private String provider;@Overrideprotected 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;} 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, 1,locationListener);}protected void onDestroy() {super.onDestroy();if (locationManager != null) {// 关闭程序时将监听器移除locationManager.removeUpdates(locationListener);}}LocationListener locationListener = new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {}@Overridepublic void onProviderEnabled(String provider) {}@Overridepublic void onProviderDisabled(String provider) {}@Overridepublic void onLocationChanged(Location location) {// 更新当前设备信息showLocation(location);}};private void showLocation(final Location location) {new Thread(new Runnable() {@Overridepublic void run() {try {// 组装反向地理编码的接口StringBuilder url = new StringBuilder();url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");url.append(location.getLatitude()).append(",").append(location.getLongitude());url.append("&sensor=false");HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(url.toString());// 在请求消息中指定语言,保证服务器返回中文数据httpGet.addHeader("Accept-Language", "zh-CN");HttpResponse httpResponse = httpClient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {HttpEntity entity = httpResponse.getEntity();String response = EntityUtils.toString(entity, "utf-8");JSONObject jsonObject = new JSONObject(response);// 获取results节点下的位置信息JSONArray resultArray = jsonObject.getJSONArray("results");if (resultArray.length() > 0) {JSONObject subObject = resultArray.getJSONObject(0);// 取出格式化的位置信息String address = subObject.getString("formatted_address");Message message = new Message();message.what = SHOW_LOCATION;message.obj = address;handler.sendMessage(message);}}} catch (Exception e) {e.printStackTrace();}}}).start();}private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case SHOW_LOCATION:String currentPosition = (String) msg.obj;positionTextView.setText(currentPosition);break;default:break;}}};}


使用百度地图

首先在布局中方式一个百度提供的MapView自定义组建,所以使用它的时候需要带上完整的包名。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <com.baidu.mapapi.map.MapView        android:id="@+id/map_view"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:clickable="true" /></LinearLayout>

还需要设置多个权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.WRITE_SETTINGS" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <uses-permission android:name="android.permission.CALL_PHONE" />    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />    <uses-permission android:name="android.permission.ACCESS_GPS" />

最终要的需要白申请的APIKey配置进去,也可以在代码中动态配置
manager = new BMapManager(this);   manager.init("SHVPoTtIpzfonPD3HCkc5sIt", null);
public class MainActivity extends Activity {private BMapManager manager;private MapView mapView;private LocationManager locationManager;private String provider;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);manager = new BMapManager(this);// API Key闇�瑕佹浛鎹㈡垚浣犺嚜宸辩殑manager.init("SHVPoTtIpzfonPD3HCkc5sIt", null);setContentView(R.layout.activity_main);mapView = (MapView) findViewById(R.id.map_view);mapView.setBuiltInZoomControls(true);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, "No location provider to use",Toast.LENGTH_SHORT).show();return;}Location location = locationManager.getLastKnownLocation(provider);if (location != null) {navigateTo(location);}}private void navigateTo(Location location) {MapController controller = mapView.getController();// 璁剧疆缂╂斁绾у埆controller.setZoom(16);GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6),(int) (location.getLongitude() * 1E6));// 璁剧疆鍦板浘涓績鐐�controller.setCenter(point);MyLocationOverlay myLocationOverlay = new MyLocationOverlay(mapView);LocationData locationData = new LocationData();// 鎸囧畾鎴戠殑浣嶇疆locationData.latitude = location.getLatitude();locationData.longitude = location.getLongitude();myLocationOverlay.setData(locationData);mapView.getOverlays().add(myLocationOverlay);// 鍒锋柊浣挎柊澧炶鐩栫墿鐢熸晥mapView.refresh();PopupOverlay pop = new PopupOverlay(mapView, new PopupClickListener() {@Overridepublic void onClickedPopup(int index) {// 鐩稿簲鍥剧墖鐨勭偣鍑讳簨浠�Toast.makeText(MainActivity.this,"You clicked button " + index, Toast.LENGTH_SHORT).show();}});// 鍒涘缓涓�涓暱搴︿负3鐨凚itmap鏁扮粍Bitmap[] bitmaps = new Bitmap[3];try {// 灏嗕笁寮犲浘鐗囪鍙栧埌鍐呭瓨涓�bitmaps[0] = BitmapFactory.decodeResource(getResources(),R.drawable.left);bitmaps[1] = BitmapFactory.decodeResource(getResources(),R.drawable.middle);bitmaps[2] = BitmapFactory.decodeResource(getResources(),R.drawable.right);} catch (Exception e) {e.printStackTrace();}pop.showPopup(bitmaps, point, 18);}@Overrideprotected void onDestroy() {mapView.destroy();if (manager != null) {manager.destroy();manager = null;}super.onDestroy();}@Overrideprotected void onPause() {mapView.onPause();if (manager != null) {manager.stop();}super.onPause();}@Overrideprotected void onResume() {mapView.onResume();if (manager != null) {manager.start();}super.onResume();}}






更多相关文章

  1. Android 设备+APP+号码信息
  2. Android根据文件路径使用File类获取文件相关信息
  3. android获取GPS位置信息
  4. Android GPS获取当前位置信息
  5. Android SmsManager(短信管理器),发送短信息
  6. Spinner下拉位置处理
  7. [Android]在Android google Map中標出自己的位置
  8. Android中获取屏幕信息DisplayMetrics的用法
  9. android获取设备存储信息

随机推荐

  1. android OkHttp3.0
  2. android 设置activity通用的全局变量(新手
  3. 用ant编译Android程序
  4. android webview加载String类型html
  5. Android涉及到的网址都记录在这把~~~~
  6. android 全屏、隐藏标题、横屏显示方法
  7. Android studio 打包混淆
  8. Android: 显示SD卡文件列表
  9. 重写gallery 的 BaseAdapter
  10. android通过Instrumentation来模拟键盘点