User android studio LBS传感器的示例代码
时间: 2023-07-08 20:49:27 浏览: 149
android传感器使用实例
5星 · 资源好评率100%
以下是一个简单的Android Studio LBS传感器示例代码,可以获取设备的经纬度信息:
```
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d("Location", "Latitude: " + latitude + " Longitude: " + longitude);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
```
该示例代码使用LocationManager来获取位置更新。在onResume方法中,它请求位置更新,如果权限没有被授予,则会请求权限。在onPause方法中,它停止位置更新。当位置更新时,会调用onLocationChanged方法,并显示经纬度信息。请注意,您需要在AndroidManifest.xml文件中添加相应的权限。
阅读全文