手机中有各种个各样的传感器,比如说距离传感器,红外线传感器,摄像头等,最近本人对GPS这个神秘的芯片有点感兴趣,于是就找了点资料,看看安卓里面内部是怎样访问GPS芯片的。
现在和大家分享一下。实现获取位置的代码
public class Chapter_Map_01Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locate();
}
private LocationManager locationManager;
private void locate()
{
TextView tv=(TextView) findViewById(R.id.mytext);
StringBuilder builder=new StringBuilder("可利用的providers:");
List<String> probiders=locationManager.getProviders(true);
LocationListener listen=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 location) {
// TODO Auto-generated method stub
}
};
for(String provider:probiders)
{
locationManager.requestLocationUpdates(provider, 0, 1000, listen);
builder.append("
").append(provider).append(":");
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null)
{
double lat=location.getLatitude();
double lng=location.getLatitude();
builder.append("(");
builder.append(lat);
builder.append(",");
builder.append(lng);
builder.append(")");
}
else
{
builder.append("没有位置信息");
}
}
tv.setText(builder);
}
}
这串代码虽然很长,但是实现了获取GPS位置的功能,有兴趣的朋友可以去试一试,本博客持续更新,内容会有改进。