的LocationListener
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText(R.string.hello_blank_fragment);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (new Utility().checkAndGrantPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, 101, "your custom message"))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
}
return textView;
}
之外的所有方法實現從onCreate
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//Todo your code
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//Todo your code
}
@Override
public void onProviderEnabled(String provider) {
//Todo your code
}
@Override
public void onProviderDisabled(String provider) {
//Todo your code
}
};
而且checkAndGrantPermission
方法是
public boolean checkAndGrantPermission(final Context context, final String permissionString, final int requestCode, String permissoinTypeMessage)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, permissionString) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permissionString)) {
// your custom dialog screen when user deny permission
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{permissionString}, requestCode);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
在活動手柄onRequestPermissionsResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 101) {
yourFragmentInstance.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
在你Framgent覆蓋onRequestPermissionsResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 101) {
if (requestCode == AppConstants.runtimePermissionCode) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
}
}
}
}
做您已編譯'com.google。 android.gms:play-services-location:10.2.4'在你的gradle中? –
是........................ – byteC0de
你可以發佈你的進口聲明 –