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

GPS学习笔记

2015-10-07 15:51 489 查看
①LocationManager类

作用与TelephonyManager、AudioManager等服务作用类似,所有GPS定位相关的服务、对象都由该对象来产生。

获取方法:Context.getSystemService(Context.LOCATION_SERVICE)

常用字段:

②LocationProvider类

作用:该类的对象是定位组件的抽象表示,通过该类的对象,可以获取定位组件的相关信息。

③Location类



作用:代表位置信息的一个抽象类,可以用来获取定位信息(比如:经纬度,高度,速度,方向等)

案例:获取定位数据

package com.example.gpstestdemo;

import android.support.v7.app.ActionBarActivity;
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.EditText;

public class MainActivity extends ActionBarActivity {
LocationManager locManager;
EditText show;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (EditText)findViewById(R.id.text);
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateView(location);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,500,8,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
updateView(locManager.getLastKnownLocation(arg0));
}

@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
updateView(null);
}

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public void updateView(Location newLocation){
if (newLocation != null){
StringBuilder sb = new StringBuilder();
sb.append("实时的位置信息:\n");
sb.append("经度:");
sb.append(newLocation.getLongitude());
sb.append("\n纬度:");
sb.append(newLocation.getLatitude());
sb.append("\n高度:");
sb.append(newLocation.getAltitude());
sb.append("\n速度:");
sb.append(newLocation.getSpeed());
sb.append("\n方向:");
sb.append(newLocation.getBearing());
show.setText(sb);
}else{
show.setText("暂时无法获取GPS信号");
}
}
}


权限申请:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gps android