I am developing an app in which I am tracking location using the tower location.
So I am using the geo location api to track the location and accessing the phone state to get the network details.
This worked well, suddenly it started giving the security exception for LOCATION_HARDWARE permission.
I also tried to give the permission in manifest as well as requesting the permission runtime. But at runtime it asks for only location and the phone state permission not for the location_hardware permission. And then it crashes with security exception.
I am not getting for which purpose it is asking for the location_hardware permission.
I am stuck up here.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpUI();
public void setUpUI()
{
TrackingJob.schedulePeriodic(); // crashing here
}
}
}
}
Tracking Job :
public class TrackingJob extends Job {
static final String TAG = "tracking";
#NonNull
#Override
protected Result onRunJob(Params params) {
Intent pi = new Intent(getContext(), GetLocationService.class);
getContext().startService(pi);
return Result.SUCCESS;
}
public static void schedulePeriodic() {
new JobRequest.Builder(TrackingJob.TAG)
.setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(15))
.setUpdateCurrent(true)
.setPersisted(true)
.build()
.schedule();
}
}
GetLocationServer :
public class GetLocationService extends IntentService {
String networkSubType = "";
SessionData mSessionData;
private SharedPreferences preferences;
public GetLocationService() {
super("GetLocationService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (ContextCompat.checkSelfPermission(GetLocationService.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(GetLocationService.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mSessionData = new SessionData(GetLocationService.this);
Calendar calendarSet = Calendar.getInstance();
Calendar calendarNow = Calendar.getInstance();
calendarSet.set(Calendar.HOUR_OF_DAY, 7); // hour
calendarSet.set(Calendar.MINUTE, 00); // minute
calendarSet.set(Calendar.SECOND, 0); // second
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.set(Calendar.HOUR_OF_DAY, 20); // hour
calendarEnd.set(Calendar.MINUTE, 00); // minute
calendarEnd.set(Calendar.SECOND, 0); // second
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(calendarNow.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String currentTime = format1.format(calendarNow.getTime());
System.out.println(currentTime);
if (calendarNow.compareTo(calendarSet) >= 0 && calendarNow.compareTo(calendarEnd) <= 0) {
TelephonyManager telephonyManager = (TelephonyManager) GetLocationService.this.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
ConnectivityManager connectivityManager = (ConnectivityManager) GetLocationService.this.getSystemService(Context.CONNECTIVITY_SERVICE);//?????????
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (cellLocation != null) {
int cellid = cellLocation.getCid();
int celllac = cellLocation.getLac();
if (activeNetInfo != null) {
networkSubType = activeNetInfo.getSubtypeName();
}
String networkOperator = telephonyManager.getNetworkOperator();
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
String networkOperatorName = telephonyManager.getNetworkOperatorName();
int type = telephonyManager.getNetworkType();
Log.d("CellLocation", cellLocation.toString());
Log.d("GSM CELL ID", String.valueOf(cellid));
Log.d("GSM Location Code", String.valueOf(celllac));
Log.d("MCC", String.valueOf(mcc));
Log.d("MNC", String.valueOf(mnc));
Log.d("NetworkOperatorName", networkOperatorName);
Log.d("radioType", String.valueOf(type));
Log.d("Network subtype name", networkSubType);
AddLocationAsyncTask addLocationAsyncTask = new AddLocationAsyncTask(GetLocationService.this);
addLocationAsyncTask.execute(mSessionData.getString("user_id", ""), String.valueOf(cellid), String.valueOf(celllac), String.valueOf(mcc), String.valueOf(mnc),
networkOperatorName, networkSubType, currentTime);
// LocationUtility.scheduleJob(getApplicationContext());
}
}
}
}
}
How can I solve this? Please help with this.
Thank you..
EDIT : Runtime permissions:
public class StartUpActivity extends AppCompatActivity {
RelativeLayout relativeLayout;
public int mShortAnimationDuration = 5000;
private Button btnRegister,btnLogin;
private final static int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 10;
private SessionData mSessionData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_up);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSessionData = new SessionData(StartUpActivity.this);
if (ContextCompat.checkSelfPermission(StartUpActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(StartUpActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(StartUpActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(StartUpActivity.this, Manifest.permission.LOCATION_HARDWARE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(StartUpActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,Manifest.permission.LOCATION_HARDWARE},
MY_PERMISSIONS_REQUEST_ACCESS_LOCATION);
}
else {
if(!mSessionData.getString("user_id","").equals(""))
{
Intent i = (new Intent(StartUpActivity.this, MainActivity.class));
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
else {
setUpUI();
listeners();
}
}
}
public void setUpUI()
{
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
}
public void listeners()
{
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = (new Intent(StartUpActivity.this, SignUpActivity.class));
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = (new Intent(StartUpActivity.this, LoginActivity.class));
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpUI();
listeners();
} else {
CommonUtils.showAlert(StartUpActivity.this,"Please accept the permissions to proceed.",getString(R.string.app_name));
ActivityCompat.requestPermissions(StartUpActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,Manifest.permission.LOCATION_HARDWARE},
MY_PERMISSIONS_REQUEST_ACCESS_LOCATION);
}
return;
}
}
}
}
Manifest permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.location.network"/>
Quoted from here:
https://developer.android.com/guide/topics/manifest/uses-feature-element.html#permissions
If your app targets Android 5.0 (API level 21) or higher and uses the
ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in order to
receive location updates from the network or a GPS, respectively, you
must also explicitly declare that your app uses the
android.hardware.location.network or android.hardware.location.gps
hardware features.
Add it like this to your AndroidManifest.xml file outside of your <application/> tag:
<uses-feature android:name="android.hardware.location.network"/>
<application>
...
</application>
If the location feature is not a "must have" feature in your app in order for the app to work properly, also add this to the uses-feature tag - android:required="false"
You still have to ask for location permission at runtime
add ACCESS_FINE_LOCATION with targeting APIs 20 and below
Related
How can I check permission for every activity ???
I am trying to make a video player app. I am trying to get External Storage on Android 11 and the lower version. When I am clicking on the button it is asking for permission for both android 11 and the lower version (ex: Kitkat). But the problem is when I am going to the next activity after granting permission and turning off the storage permission from settings in the background. It was not asking for any permission for this new activity.
If anyone has any solution please help me I was shared my code bellow
My permission activity(MainActivity.java) and I want to check permission in (activity_allow_access.java).
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 100;
final static int REQUEST_CODE = 333;
private Button signIn;
public static String PREFS_NAME="MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = findViewById(R.id.button);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
});
}
private void requestPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package",this.getPackageName(),null);
intent.setData(uri);
storageActivityResultLauncher.launch(intent);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
storageActivityResultLauncher.launch(intent);
}
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
}
}
private ActivityResultLauncher<Intent> storageActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
if(Environment.isExternalStorageManager()){
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
else{
Toast.makeText(MainActivity.this, "storage permission required", Toast.LENGTH_SHORT).show();
}
}
}
}
);
public boolean checkPermission(){
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}else {
int write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED;
}
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
#SuppressLint("MissingSuperCall")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.length >0){
boolean write = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean read = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(write && read) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
}
}
AllowAccessActivity.java
public class AllowAccessActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allow_access);
}
}
This question already has answers here:
"gps" location provider requires ACCESS_FINE_LOCATION permission for android 6.0
(4 answers)
Android “gps requires ACCESS_FINE_LOCATION” error
(2 answers)
Closed 4 years ago.
I am using GPS in my application, When I compile and run app crashes with error of
javal.lang.SecurityException:"gps"location provider requires ACCESS_FINE_LOCATOIN.permission
Althought I have already included permission inmy Manifest File. I have also asked for runtime permission in activity but still I'm getting the error
Here is the screenshot of logcat
The gps method
private void checkGPS() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
buildAlertMessageNoGps();
}
my manifest file is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.nepalpolice.cdp">
<uses-permission android:name="android.permissoin.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
My whole code is
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnInfoWindowClickListener, LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate started");
super.onCreate(savedInstanceState);
setInternalStorage();
// Read selected location from Extra of passed intent
selectedLocationData = (LocationData) getIntent().getSerializableExtra(InternalStorage.SEL_LOC_DATA_KEY);
if(selectedLocationData!=null)
internalStorage.writeLocationData(selectedLocationData,TARGET_ID);
checkGPS();
checkAndConnect();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
this.googleMap.setMyLocationEnabled(true);
googleApiClient = new GoogleApiClient.Builder(this) // This code is for updating current location
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
zoom(15, 90, 40);
if (selectedLocationData != null && selectedLocationData.isReal()) {
setMarker(selectedLocationData.getLatitude(), selectedLocationData.getLongitude());
startLocationRequest(); // If location is passed from StartActivity, start checking locations
}
centerMap();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATIONS);
}
}
}
private void zoom(float zoom, float bearing, float tilt) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(zoom) // Sets the zoom
.bearing(bearing) // Sets the orientation of the camera to east
.tilt(tilt) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_FINE_LOCATIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
googleApiClient = new GoogleApiClient.Builder(this) // This code is for updating current location
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
}
} else {
Toast.makeText(getApplicationContext(), "this app requires location permissions to be granted", Toast.LENGTH_LONG).show();
ActivityCompat.finishAffinity(MapActivity.this);
System.exit(0);
}
break;
}
}
private void buildAlertMessageNoWifi() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
void startLocationRequest() {
checkGPS();
isTracking = true;
userNotified = false;
interval = MIN_INTERVAL;
internalStorage.writeInterval(interval);
// Manage wake up alerts
alarm = new AlarmReceiver();
alarm.setAlarm(this, interval);
renewLocationRequest();
// Hide search options
findViewById(R.id.button).setVisibility(View.GONE);
findViewById(R.id.place_autocomplete_fragment).setVisibility(View.GONE);
// Toggle tracking button view
Button button = (Button) findViewById(R.id.startpause);
button.setBackgroundColor(Color.RED);
button.setText("Pause tracking");
if (locationRequest != null) // TODO should check why it happens
Log.v("startLocationRequest", "" +
"\ninterval:" + String.valueOf(locationRequest.getInterval()) +
"\nfastest interval:" + String.valueOf(locationRequest.getFastestInterval()));
}
void stopLocationRequest() {
if (googleApiClient != null && googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
locationRequest = null;
isTracking = false;
alarm.releaseWakeLock();
alarm = null;
Button button = (Button) findViewById(R.id.startpause);
button.setBackgroundColor(Color.GREEN);
button.setText("Start tracking");
Log.i("stopLocationRequest", "stopped successfully");
}
public void enableWiFi() {
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
Toast.makeText(getApplicationContext(), "Wi-fi connecting..", Toast.LENGTH_LONG).show();
}
private void checkGPS() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
buildAlertMessageNoGps();
}
public void checkAndConnect() {
if (!checkedWiFi) {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm != null) {
if (!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected())) {
buildAlertMessageNoWifi();
}
}
checkedWiFi = true;
}
}
Please Help
I have added READ_PHONE_STATE permission in my project.
Scenario:
I am just opening my application and I get Permission alert “Allow My Application to make and manage phone calls ?"
Now I am moving my application in background and again opening by tap on My Application icon
Result: “Allow My Application to make and manage phone calls ?" Permission pop up get disappears.
Can any one tell why this behaviour?
Note: I am using launchMode="singleInstance" and when using launchMode="standard" all is working fine.
Sharing my code :
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
public class MainActivity extends AppCompatActivity {
public static final Integer REQUEST_CODE_FOR_PERMISSION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
public static void askForPermission(Activity context, String permission, Integer requestCode) {
if ((Build.VERSION.SDK_INT >= 23) && (context != null) && (TextUtils.isEmpty(permission) == false)) {
ActivityCompat.requestPermissions(context, new String[]{permission}, requestCode);
}
}}
Based on singleTask behaviour
If an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance.
https://developer.android.com/guide/components/activities/tasks-and-back-stack#TaskLaunchModes
I was able to fix this issue by handling the code in
onNewIntent(Intent intent)
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
Try this,
public class MainActivity extends AppCompatActivity {
public static final Integer REQUEST_CODE_FOR_PERMISSION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#override
private void onResume(){
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
public static void askForPermission(Activity context, String permission, Integer requestCode) {
if ((Build.VERSION.SDK_INT >= 23) && (context != null) && (TextUtils.isEmpty(permission) == false)) {
ActivityCompat.requestPermissions(context, new String[]{permission}, requestCode);
}
}}
Call finish() in onBackPressed()
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
This will launch activity again and your code will work in onCreate()
Use Runtime Permission like this:
public class MainActivity extends Activity {
private static final int PERMISSION_REQUEST_CODE = 200;
Context context;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
activity = this;
setContentView(R.layout.activity_splash);
if (!checkPermission()) {
OpenActivity();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
OpenActivity();
}
}
}
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, READ_PHONE_STATE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("STORAGE permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(SplashActivityANother.this, new String[]{READ_PHONE_STATE,
}, PERMISSION_REQUEST_CODE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE
}, PERMISSION_REQUEST_CODE);
}
} else {
OpenActivity();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (permissions.length > 0 && grantResults.length > 0) {
boolean flag = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
flag = false;
}
}
if (flag) {
OpenActivity();
} else {
finish();
}
} else {
finish();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void OpenActivity() {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
}
and Add
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> in to menifist file.
Hope this Helps you
I have an activity in which I have a text view where I want to display the distance between the user's current location and a specific address. I have the Latitude and Logitude of the address but my issue is getting the user's location. My target is when the activity is created that's when I want to get his location' without pressing any button. I have tried multiple ways: getLastKnownLocation, onLocation changed etc, but the value returned is always null.
It's important to note that I am running the app on an emulator.
Sample code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_list);
Bundle bundleUser = getIntent().getExtras();
final String owneruser = bundleUser.getString("username");
Bundle bundleType = getIntent().getExtras();
String type = bundleType.getString("type");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final TextView t = (TextView) findViewById(R.id.textView2);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
t.append("\n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
final Location userLocation = new Location("");
userLocation.setLatitude(latitude);
userLocation.setLongitude(longitude);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
update();
break;
default:
break;
}
}
void update(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
}
else {
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
}
implement your activity to LocationListener :
public class MyActivity extends AppCompatActivity implements LocationListener {
private Location userLocation = new Location("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
#Override
public void onLocationChanged(Location location) {
if(location != null){
userLocation.setLatitude(location.getLatitude());
userLocation.setLongitude(location.getLongitude());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
TRY this to grant permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation 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.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
}
}
and add this in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I am currently developing an app together with a friend of mine and I'm using the following code to acquire my current location:
public class AdressPopup extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = AdressPopup.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
TextView textViewCord;
Button okayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adress_finder);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// GUI items:
textViewCord = (TextView) findViewById(R.id.textViewCord);
okayButton = (Button) findViewById(R.id.button);
// Terminate window upon clicking 'okayButton':
okayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
// How much to cover of the window..
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .6), (int) (height * .35));
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
Locale svLocale = new Locale("sv", "SE");
//Get address based on location:
try {
Geocoder geo = new Geocoder(AdressPopup.this.getApplicationContext(), svLocale.getDefault());
List<android.location.Address> addresses;
addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.isEmpty()) {
textViewCord.setText("Waiting for Location");
} else {
if (addresses.size() > 0) {
final String postalCode = addresses.get(0).getPostalCode();
final String streetName = addresses.get(0).getThoroughfare();
// final String cityName = addresses.get(0).getLocality();
StoreBackend.lookupStoreName(postalCode, new StoreBackend.Callback<String>() {
#Override
public void acceptResult(String name) {
textViewCord.append(postalCode + " (" + streetName + ") " + "\n\n" + "Din butik" + ": " + name);
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "Location services connected.");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//do nothing
} else if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
// Log.d("Coordinates: ", location.getLatitude() + "," + location.getLongitude());
onLocationChanged(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
}
We are using android studio together with bitbucket (where our repository for this project is located). This works perfectly well when I export the .apk file to my samsung galaxy s4 device. However, when my friend does the same from his android studio environment and tries this functionality on his samsung galaxy s7 (mind you, we are working with identical code) it's not working.
He is getting a null value when requesting a new location on the following line:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
These permissions are present in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
and the build that is being used for the play-service is '6.5.87'. Any help on the matter would be greatly appreciated.