如何解决呼叫需要权限[Android]
我在解决当前位置问题时遇到问题,LocationManager给出了以下错误: 我添加了此代码,但它需要返回值。我应该只返回null还是 以下是我所在位置的代码:如何解决呼叫需要权限[Android],android,locationmanager,Android,Locationmanager,我在解决当前位置问题时遇到问题,LocationManager给出了以下错误: 我添加了此代码,但它需要返回值。我应该只返回null还是 以下是我所在位置的代码: public class GPSService extends Service implements LocationListener { // saving the context for later use private final Context mContext; // if GPS is enabled boolea
public class GPSService extends Service implements LocationListener {
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
/**
* Returs the Location
*
* @return Location or null if no location is found
*/
public Location getLocation() {
try {
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
askUserToOpenGPS();
}
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
}
/**
* Gives you complete address of the location
*
* @return complete address in String
*/
public String getLocationAddress() {
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
return ("IO Exception trying to get address:" + e1);
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
}
} else {
return "Location Not available";
}
}
/**
* get latitude
*
* @return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* get longitude
*
* @return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
try {
mLocationManager.removeUpdates(GPSService.this);
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
}
}
/**
* show settings to open GPS
*/
public void askUserToOpenGPS() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use use location services?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
/**
* Updating the location when location changes
*/
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
公共类GPSService扩展服务实现LocationListener{
//保存上下文以供以后使用
私有最终上下文mContext;
//如果启用了GPS
布尔值isGPSEnabled=false;
//如果网络已启用
布尔值isNetworkEnabled=false;
//如果位置坐标可用GPS或网络
公共布尔值isLocationAvailable=false;
//位置和坐标
位置;
双重疲劳;
双倍长度;
//下一次更新的最短时间波动(毫秒)
私人静态最终长时间=30000;
//下次更新的最小距离波动(以米为单位)
私人静态最终长途=20;
//声明位置管理器
受保护的位置管理器mLocationManager;
公共GPSService(上下文){
this.mContext=上下文;
mLocationManager=(LocationManager)mContext
.getSystemService(位置服务);
}
/**
*重新定位
*
*@返回位置,如果找不到位置,则返回null
*/
公共位置getLocation(){
试一试{
//如果到达这里意味着,我们也无法获得位置
//从全球定位系统而不是网络,
如果(!isGPSEnabled){
//所以要求用户打开GPS
askUserToOpenGPS();
}
mLocationManager=(LocationManager)mContext
.getSystemService(位置服务);
//获取GPS状态
isGPSEnabled=mLocationManager
.isprovidenabled(LocationManager.GPS\U提供商);
如果(Build.VERSION.SDK_INT>=23&&
ContextCompat.checkSelfPermission(getApplicationContext(),android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ContextCompat.checkSelfPermission(getApplicationContext(),android.Manifest.permission.ACCESS\u rough\u LOCATION)!=PackageManager.permission\u已授予){
返回;
//如果启用了GPS,请使用GPS服务获取纬度/经度
如果(isGPSEnabled){
mLocationManager.RequestLocationUpdate(
LocationManager.GPS_提供程序、时间、距离、此);
if(mLocationManager!=null){
mLocation=mLocationManager
.getLastKnownLocation(LocationManager.GPS\U提供商);
如果(mLocation!=null){
mLatitude=mLocation.getLatitude();
mlongalite=mLocation.getLongitude();
isLocationAvailable=true;//设置一个
//位置是可用的
返回位置;
}
}
}
//如果我们到达这一部分,这意味着GPS无法获取数据
//任何地点
//获取网络状态
isNetworkEnabled=mlLocationManager
.isProviderEnabled(LocationManager.NETWORK_提供商);
if(可联网){
mLocationManager.RequestLocationUpdate(
LocationManager.NETWORK_提供程序、时间、距离、此);
if(mLocationManager!=null){
mLocation=mLocationManager
.getLastKnownLocation(LocationManager.网络提供商);
如果(mLocation!=null){
mLatitude=mLocation.getLatitude();
mlongalite=mLocation.getLongitude();
isLocationAvailable=true;//设置一个
//位置是可用的
返回位置;
}
}
}
}捕获(例外e){
e、 printStackTrace();
}
//如果到达此处意味着位置不可用,则设置
//标志为假
isLocationAvailable=false;
返回null;
}
}
/**
*提供该位置的完整地址
*
*@返回字符串形式的完整地址
*/
公共字符串getLocationAddress(){
如果(isLocationAvailable){
Geocoder Geocoder=新的地理编码器(mContext,Locale.getDefault());
//从输入参数列表中获取当前位置
//创建包含结果地址的列表
列表地址=空;
试一试{
/*
*返回1个地址。
*/
地址=地理编码器.getFromLocation(mLatitude,mLongitate,1);
}捕获(IOE1异常){
e1.printStackTrace();
返回(“试图获取地址的IO异常:”+e1);
}捕获(IllegalArgumentException e2){
//要在日志中发布的错误消息
String errorString=“非法参数”
+双.toString(mLatitude)+“,”
+双.toString(长度)
+“传递到地址服务”;
e2.printStackTrace();
返回错误字符串;
}
//如果反向地理代码返回一个地址
if(addresses!=null&&addresses.size()>0){
//获取第一个地址
地址=地址。获取(0);
/*
*格式化第一行地址(如果可用)、城市和
*国名。
*/
字符串地址text=String.format(
“%s,%s,%s”,
//如果有街道地址,请添加它
address.getMaxAddressLineIndex()>0?地址
.getAddressLine(0):“”,
//地点通常是一个城市
address.getLocation(),
//地址所在国
address.getCountryName());
//返回文本
返回地址文本;
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionCheck1 = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED && permissionCheck1 == PackageManager.PERMISSION_GRANTED) {
startService(new Intent(MainActivity.this, TrackingService.class));
locationRelatedServices();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, PermissionInts.LOCATION_CODE);
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PermissionInts.LOCATION_CODE:
locationRelatedServices();
}
break;
}
public void getPermissionLocation(){
// 1) Use the support library version ContextCompat.checkSelfPermission(...) to avoid
// checking the build version since Context.checkSelfPermission(...) is only available
// in Marshmallow
// 2) Always check for permission (even if permission has already been granted)
// since the user can revoke permissions at any time through Settings
if (ContextCompat.checkSelfPermission(PrimecardSplashscreen.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(PrimecardSplashscreen.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// The permission is NOT already granted.
// Check if the user has been asked about this permission already and denied
// it. If so, we want to give more explanation about why the permission is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show our own UI to explain to the user why we need to read the contacts
// before actually requesting the permission and showing the default UI
}
}
}
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
AppData.READ_LOCATION_PERMISSIONS_REQUEST);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Make sure it's our original ACCESS_FINE_LOCATION request
if (requestCode == AppData.READ_LOCATION_PERMISSIONS_REQUEST) {
if (grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(PrimecardSplashscreen.this, "Read Location permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(PrimecardSplashscreen.this, "Read Location permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}