这是我的代码
package com.example.decimateglitchlocation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.Manifest;
import android.widget.Toast;
import android.content.pm.PackageManager;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude, longitude;
protected boolean gps_enabled, network_enabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
try{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} catch (SecurityException securityException) {
txtLat.setText("Error");
}
}//end of if
else{txtLat.setText("Error2");}
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.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");
}
}
我在清单中使用正确的权限粗略位置,精确位置和互联网。它仍然显示错误2,检查权限是奇怪的行为。如果可以,请帮助解决这个问题。
我已经在android开发人员和堆栈溢出上一遍又一遍地检查,并且检查权限“似乎不是直截了当”。我可能不只是得到它的主旨。
谢谢,
真诚
肖恩
答案 0 :(得分:0)
从Android M开始只是在清单中声明权限是不够的。您必须实现权限模型才能成功获得授予的权限。
查看您的代码,您错过了权限请求。请遵循此official guile并实施权限模型以获得预期结果。
ActivityCompat.requestPermissions(thisActivity,
new String[] {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
检查结果如下:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
//pare grantResults
return;
}
}
}