Rx Java Subscriber never gets onNext event from location updates - java

I'm trying to use this library: https://android-arsenal.com/details/1/3291 to get user's location. I did I think everything the sample shows but my Observable/Subscriber never triggers.
Here's my activity:
public class GpsActivity extends AppCompatActivity/* implements LocationListener*/ {
final android.location.Location[] lastKnown = new android.location.Location[2];
LocationManager manager;
boolean exitLoop = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.no_gps);
ButterKnife.bind(this);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getLocation();
}
private void getLocation() {
//TODO zmienić UI
boolean gpsPermission = checkPermissions();
if (!gpsPermission) {
Log.d(getClass().getSimpleName(), "No GPS permissions!");
//TODO Handle permissions result
requestPemissions();
return;
}
boolean gpsEnabled = checkSettings();
if (!gpsEnabled) {
Log.d(getClass().getSimpleName(), "GPS not enabled!");
//TODO Handle settings result
buildAlertMessageNoGps();
return;
}
subscribeForLocation(25f, this);
}
private void requestPemissions() {
Log.d(getClass().getSimpleName(), "Requesting permissions...");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, IntentHelper.PERMISSION_GPS);
}
Log.d(getClass().getSimpleName(), "Done.");
}
private boolean checkSettings() {
Log.d(getClass().getSimpleName(), "Checking settings...");
return !manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
private boolean checkPermissions() {
Log.d(getClass().getSimpleName(), "Checking permissions...");
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void buildAlertMessageNoGps() {
Log.d(getClass().getSimpleName(), "Showing GPS settings alert...");
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), IntentHelper.GPS_SETTINGS);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public void subscribeForLocation(float accuracy, final Context context) {
Log.d(getClass().getSimpleName(), "Subscribing for updates...");
final LocationRequestBuilder locationRequestBuilder = new LocationRequestBuilder(this);
locationRequestBuilder.addLastLocation(LocationManager.GPS_PROVIDER, new LocationTime(30, TimeUnit.SECONDS), false)
.addRequestLocation(LocationManager.GPS_PROVIDER, new LocationTime(10, TimeUnit.SECONDS))
.create().subscribe(new Subscriber<android.location.Location>() {
#Override
public void onCompleted() {
saveLocation();
}
#Override
public void onError(Throwable e) {
Log.d(getClass().getSimpleName(), e.toString());
}
#Override
public void onNext(android.location.Location location) {
final String name = Thread.currentThread().getName();
Log.d(getClass().getSimpleName(), location != null ? location.toString() : "Location is empty =(");
}
});
}
The output I get from my logs is this:
D/GpsActivity: Checking permissions...
D/GpsActivity: Checking settings...
D/GpsActivity: Subscribing for updates...
And then it just sits there doing nothing. This is my first time using Rx so not really sure what I should do in this situation.

Well first of all you have wrong if statement - double negation.
boolean gpsEnabled = checkSettings();
if (!gpsEnabled) {
Log.d(getClass().getSimpleName(), "GPS not enabled!");
//TODO Handle settings result
buildAlertMessageNoGps();
return;
}
Keep in mind that after subscribing you will receive only one result since observable will emit onCompleted after first received location because of the:
return result.firstOrDefault(defaultLocation)
.observeOn(scheduler);
Notice that nothing will happen after user will grant permission because you are performing "return" from function if permission is not granted already. You can handle subscribing after granting permission by overriding following method:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Depends on your needs you may want to be constantly notified about current location. One of the solution is to simply modified library that you are using (what is more preferable solution) and "fix" onCompleted event emitted by Observable. Another way is to subscribe every period of time:
Observable.interval(5, TimeUnit.SECONDS)
.compose(this.<Long>bindToLifecycle()) //google rx trello github
.subscribe(new Action1<Long>() {
#Override
public void call(Long aLong) {
subscribeForLocation(25f, GpsActivity.this);
}
});

Related

How to show AlertDialog as permission rationale

I have two activities: a Main, as well a RuntimePermissionManager, which is started first whenever my app is opened.
The app works as expected when the user allows the runtime permission, but when they deny it, instead of the AlertDialog showing up with the permission rationale, the permission dialog is closed completely, and I just get an infinite splash screen (since I have set it to always be on screen during the lifetime of its parent activity).
I have copied the permission logic straight from the RuntimePermissionsBasic example bundled with Android Studio, and just replaced the Snackbar with an AlertDialog, so I don’t see why my app isn’t working.
Here’s the complete RuntimePermissionManager activity for reference.
Thanks.
public class RuntimePermissionManager extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = "RuntimePermissionManager";
private static final String PERMISSION = Manifest.permission.WRITE_EXTERNAL_STORAGE;
private static final int PERMISSION_ID = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
final SplashScreen splashScreen = SplashScreen.installSplashScreen(this);
super.onCreate(savedInstanceState);
// This ensures no hiccups while the splash screen is active.
splashScreen.setKeepOnScreenCondition(() -> true);
checkRuntimePermissionStatus();
ThreadManager.unpackCriticalAssets(getApplicationContext());
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Runtime permission has been granted.");
startMainActivity();
} else {
Log.e(TAG, "Runtime permission has been denied.");
}
}
}
private void checkRuntimePermissionStatus() {
if (ActivityCompat.checkSelfPermission(this, PERMISSION) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Runtime permission has been granted.");
startMainActivity();
} else {
requestRuntimePermission();
}
}
private void requestRuntimePermission() {
System.out.println(ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION));
if (ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION)) {
System.out.println("HERE1");
showPermissionRationaleDialog(R.string.permission_rationale_title, R.string.permission_rationale_message);
} else {
Log.e(TAG, "Runtime permission has been denied.");
ActivityCompat.requestPermissions(this, new String[]{PERMISSION}, PERMISSION_ID);
}
}
private void showPermissionRationaleDialog(final int title, final int message) {
System.out.println("HERE2");
AlertDialog.Builder builder = new AlertDialog.Builder(RuntimePermissionManager.this);
builder.setTitle(title).setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(RuntimePermissionManager.this, new String[]{PERMISSION}, PERMISSION_ID);
}
});
builder.create().show();
}
private void startMainActivity() {
Intent intent = new Intent(this, Main.class);
startActivity(intent);
}
}

onRequestPermissionResult not being called in AppCompatActivity

I am trying to request some permission for my app inside the launcher activity. This activity only checks for permissions and prompts the user asking for missing permission. What I want to do is after 1.5 seconds, if the user was prompted and accepted/denied the permissions required, the main activity is started, displaying the dashboard of the application. Now, the problem is that onRequestPermissionResult is not called no matter what I do and I don't understand where the problem comes from. I mention that the permissions are requested successfully, the user being prompted and being able to accept them or deny them, but the callback is not triggered somehow.
Here is my activity code:
public class LauncherActivity extends AppCompatActivity {
public static final String TAG = LauncherActivity.class.getSimpleName();
private boolean permissionsGiven;
private static final String[] REQUIRED_PERMISSIONS =
new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
if (!hasPermissions(this, REQUIRED_PERMISSIONS)) {
permissionsGiven = false;
Log.d(TAG, "onCreate: app does not have all the required permissions. Requesting permissions...");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(
this,
REQUIRED_PERMISSIONS,
REQUEST_CODE_REQUIRED_PERMISSIONS
);
}
} else {
permissionsGiven = true;
}
Runnable enterApplication = new Runnable() {
#Override
public void run() {
while (!permissionsGiven);
SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
boolean signedIn = loginPreferences.getBoolean("signedIn", false);
if (!signedIn) {
Log.d(TAG, "onCreate: user is not signed in. Sending him to login activity...");
sendUserToLoginActivity();
} else {
sendUserToMainActivity();
}
}
};
Handler launcherHandler = new Handler();
launcherHandler.postDelayed(enterApplication, 1500);
}
private static boolean hasPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
#CallSuper
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode != REQUEST_CODE_REQUIRED_PERMISSIONS) {
return;
}
permissionsGiven = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Missing permissions", Toast.LENGTH_LONG).show();
finish();
return;
}
}
recreate();
}
private void sendUserToLoginActivity() {
Log.d(TAG, "sendUserToLoginActivity: starting login activity...");
Intent loginIntent = new Intent(LauncherActivity.this, SignInActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginIntent);
finish();
}
private void sendUserToMainActivity() {
Log.d(TAG, "sendUserToMainActivity: starting main activity...");
Intent mainIntent = new Intent(LauncherActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
}
Can anyone help me understand what am I doing wrong and how can I trigger onRequestPermissionsResult so I can start the next activity inside the app?
recreate();
I never saw that method.
Dont call it for a test and place a Toast instead.
I wonder how you know that it is not triggered.
Further i would not use a thread that is waiting for a variable to change its value.
Further you dont need threads at all. Just call the code in onCreate or onRequestPermissionsResult. You can place all that code in a function.

Location tracking in the background Android

I got some problems to keep a location tracking for my Android app.
The service we developed are all working, but depending on the phones and the API level, they are killed soon or later.
My purpose is to notify a user when he is getting out of a certain range, and this is working when the app is running.
This is the service that calculates when the user is in or out of the zone:
public class GeoFenceService extends BaseService {
#Inject
GeoFenceRepository geoFenceRepository;
SettingValueService settingValueService = new SettingValueService();
GeoFence geoFence;
private GeofencingClient mGeofencingClient;
PendingIntent mGeofencePendingIntent;
List<Geofence> mGeofenceList = new ArrayList<>();
public GeoFenceService() {
super();
Injector.getInstance().getAppComponent().inject(this);
}
public Observable<GeoFence> saveGeofence(GeoFence geoFence) {
if (geoFence.getId() == null)
geoFence.setId(CommonMethods.generateUuid());
commitToRealm(geoFence);
if (Application.getHasNetwork())
return geoFenceRepository.saveGeofence(geoFence);
else
return Observable.just(null);
}
public Observable<GeoFence> getGeofence() {
return geoFenceRepository.getGeofence();
}
public GeoFence getGeofenceFromRealm() {
Realm realm = Realm.getDefaultInstance();
RealmQuery<GeoFence> query = realm.where(GeoFence.class);
GeoFence result = query.findFirst();
if (result != null)
return realm.copyFromRealm(result);
return null;
}
public void initGeoFence(Context context) {
SettingValue autoCloking = settingValueService.getSettingByName("auto_clocking");
if (autoCloking != null && autoCloking.getValue().equals("true")) {
if (mGeofencingClient == null)
mGeofencingClient = LocationServices.getGeofencingClient(context);
geoFence = getGeofenceFromRealm();
if (geoFence != null) {
addGeofence(geoFence, context);
}
}
}
#SuppressLint("MissingPermission")
public void addGeofence(GeoFence geofence, Context context) {
mGeofenceList.clear();//only 1 geofence at the same time.
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(geofence.getId())
.setCircularRegion(
geofence.getLatitude(),
geofence.getLongitude(),
(float) geofence.getRadius()
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setLoiteringDelay(30000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT | Geofence.GEOFENCE_TRANSITION_DWELL)
.build());
mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent(context));
}
private PendingIntent getGeofencePendingIntent(Context context) {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(context, GeofencingService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
mGeofencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT);
builder.addGeofences(mGeofenceList);
return builder.build();
}
public void removeGeofence(Context context) {
if (mGeofencingClient != null)
mGeofencingClient.removeGeofences(getGeofencePendingIntent(context));
}
}
Even if this was working in the background we made a service to wake up the GPS of the phone every 60 sec following the advice of this question.
This is the service we made:
public class UpdateLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "UpdateLocationService";
private static final int LOCATION_INTERVAL = 60000;
private Context mContext;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private FusedLocationProviderApi fusedLocationProviderApi;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
mContext = this;
getLocation();
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
try {
if (googleApiClient != null) {
googleApiClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getLocation() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(LOCATION_INTERVAL);
locationRequest.setFastestInterval(LOCATION_INTERVAL);
fusedLocationProviderApi = LocationServices.FusedLocationApi;
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle arg0) {
// Location location =
fusedLocationProviderApi.getLastLocation(googleApiClient);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int arg0) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(mContext, "User location :"+location.getLatitude()+" , "+location.getLongitude(), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
}
and finally this is the call in our main activity:
if (checkGpsProviderEnabled()) {
geoFenceService.initGeoFence(this);
Intent msgIntent = new Intent(this, GeofencingService.class);
startService(msgIntent);
startService(new Intent(this,UpdateLocationService.class));
}
Of course, we implement the authorization for Localisation and service déclaration in our AndroidManifest
And everything is working fine when the app isn't in the foreground
The foreground is working on some device but not all, and I wanted to know if I can do something more to force our services to run all the time in the background
Thanks in advance

How to get coordinates once you've navigated back from turning location on?

Whats the best way to get the getCoordinates method to run, once you return from the intent that was used in order to turn the location on. When you backpress once you have turned the location on, what happens in the activity lifecylce and where would be the best place to then call the getCoordinates method once you have returned from turning the location on, or even to first check if the location is on and only if it is then run getCoordinates method?
checkLocationOn
public void checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
getCoordinates
public void getCoordinates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
latitude = Double.toString(lat);
longitude = Double.toString(lng);
SharedPreferences.Editor e = preferences.edit();
e.putString("myLats",latitude);
e.putString("myLngs",longitude);
e.commit();
}
});
}
onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.job_search_fragment, container, false);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
checkLocationOn();
getCoordinates();
//Please help here
return v;
}
Override onResume and call both checkLocationOn(); and getCoordinates(); from there.
If you are requesting continuous location updates, you can remove the request it in onPause method.
Thanks arsena, i just changed the checkLocationOn() to a boolean and then in the onResume() if the checkLocationOn() is true then i call the getCoordinate() like so.
public boolean checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.show();
return false;
}else{
return true;
}
}
then in onResume()
#Override
public void onResume() {
super.onResume();
if(checkLocationOn()){
getCoordinates();
}
}
its working now

Android CALL_PHONE runtime permission

i have method for get runtime permission i searched for that long but still have no answer can anyone help me to modify my code ? cause its never show request dialog for get user permission after user accept permission move to next activity
here my code that i made but some how its never made a request
public class perm extends AppCompatActivity {
private static final int REQUEST_PERMISSION_SETTING = 200;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dash);
isPermissionGranted();
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PERMISSION_SETTING);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(permissions.length == 0){
return;
}
boolean allPermissionsGranted = true;
if(grantResults.length>0){
for(int grantResult: grantResults){
if(grantResult != PackageManager.PERMISSION_GRANTED){
allPermissionsGranted = false;
break;
}
}
}
if(!allPermissionsGranted){
boolean somePermissionsForeverDenied = false;
for(String permission: permissions){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
//denied
Log.e("denied", permission);
}else{
if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){
//allowed
Log.e("allowed", permission);
} else{
//set to never ask again
Log.e("set to never ask again", permission);
somePermissionsForeverDenied = true;
}
}
}
if(somePermissionsForeverDenied){
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Permissions Required")
.setMessage("You have forcefully denied some of the required permissions " +
"for this action. Please open settings, go to permissions and allow them.")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setCancelable(false)
.create()
.show();
}
} else {
switch (requestCode) {
//act according to the request code used while requesting the permission(s).
}
}
}
}

Categories