如何在Android中获取位置及其温度?
在这里,我使用“位置管理器”查找当前位置,使用“传感器管理器”获取当前温度。当我使用“位置管理器”应用程序崩溃时,显示以下错误消息: 原因:java.lang.SecurityException:“网络”位置提供程序需要访问\u粗略\u位置或访问\u精细\u位置权限 以下是“位置管理器”和“传感器管理器”的代码如何在Android中获取位置及其温度?,android,android-sensors,android-location,Android,Android Sensors,Android Location,在这里,我使用“位置管理器”查找当前位置,使用“传感器管理器”获取当前温度。当我使用“位置管理器”应用程序崩溃时,显示以下错误消息: 原因:java.lang.SecurityException:“网络”位置提供程序需要访问\u粗略\u位置或访问\u精细\u位置权限 以下是“位置管理器”和“传感器管理器”的代码 **MainActivity.java** public class MainActivity extends AppCompatActivity implements Sen
**MainActivity.java**
public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private SensorManager mSensorManager;
private Sensor mTemperature;
private final static String NOT_SUPPORTED_MESSAGE = "Sorry, sensor not available for this device.";
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_DISTANCE_CHANGE_FOR_UPDATES, MIN_TIME_BW_UPDATES, this);
}
@Override
public void onLocationChanged(Location location) {
locationTextView.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH){
mTemperature= mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); // requires API level 14.
}
if (mTemperature == null) {
temperatureTextView.setText(NOT_SUPPORTED_MESSAGE);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mTemperature, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
float ambient_temperature = event.values[0];
temperatureTextView.setText(String.valueOf(ambient_temperature) + getResources().getString(R.string.celsius));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
}
将此添加到android清单文件:
别忘了申请位置许可 您是否已请求运行时权限,并在设置中为您的应用启用了位置和传感器?请检查。请求运行时权限以使用sension和location 与所有SDK版本兼容(android.permission.ACCESS\u FINE\u位置在android M中成为危险权限,需要用户手动授予) 在Android M ContextCompat.checkSelfPermission(…)下面的Android版本中,如果在AndroidManifest.xml中添加这些权限,则始终返回true) < 使用权限android:name=“android.permission.ACCESS\u FINE\u LOCATION”/ 公共静态final int MY_PERMISSIONS_REQUEST_LOCATION=99
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
Then call the checkLocationPermission() method in onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLocationPermission();
}
然后可以使用onResume()和onPause(),与问题中的用法完全相同。这是一个更简洁的浓缩版本:
@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
}
@Override
protected void onPause() {
super.onPause();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(this);
}
}
请点击链接了解更多信息
您忘记在清单文件中添加权限。只要加上这个问题就会解决。非常感谢。它对我的位置有效,但对温度无效。请帮我查一下房间里的温度。