How to add location class to android app? - java

I have an app that sends your location on SMS and I need to implement the location.
I tested some code on another project and the code worked well.
I got the code from the test project and made a new class and put the code there but something isn't working.
public class LocMng extends MainActivity {
private Button b;
private TextView t;
private TextView k;
private LocationManager locationManager;
private LocationListener listener;
final int SEND_SMS_PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
b = (Button) findViewById(R.id.btnpol);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
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);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button(){
// 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);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 10000, 10, listener);
}
});
}
}
When I press the button nothing happens.
Here is the whole file if needed
https://github.com/Tony459/SO-ASt/tree/master/For%20SO
Somethings in the code are Turkish but they are not important

you are not requesting the location correctly , try to get the location this way :
private Location getLastKnownLocation() {
LocationManager mLocationManager;
mLocationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}

Your checking code should probably look more like this:
if ( Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
If the 'If' statement is false, then it doesn't return and the b.setOnClickListener gets executed.

Related

Send location via sms Button doesn't work - android studio

I tried to send my location via SMS, but the button doesn't work.
The button was working fine before I added the code of getting current location.
Can you please help me to fix that? I tried many solutions that I found in this website, but it doesn't work with me.
I am totally new to Android Studio, so I don't know how to write my code that it will work the way I want it.
private LocationManager locationManager;
private LocationListener locationListener;
String[] appPermissions = {
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.SEND_SMS
};
private static final int PERMISSIONS_REQUEST_CODE = 123;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
double x,y;
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkAndRequestPermissons()) {
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
x = location.getAltitude() ;
y = location.getLongitude();
Log.d("Location", location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxx", null, "Je suis en danger, voici ma localisation : https://www.google.com/maps/search/?api=1&query=" + x + "," + y , null, null);
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
private boolean checkAndRequestPermissons() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions)
{
if (ContextCompat.checkSelfPermission(this,perm) != PackageManager.PERMISSION_GRANTED)
{
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray(
new String[listPermissionsNeeded.size()]),PERMISSIONS_REQUEST_CODE
);
return false;
}
return true;
}

GPS location data does not match the location of AVD

I write a simple code to show and update the latitude and longitude through GPS. The problem is they remain unchanged when I change the location of AVD.
public class PocketSphinxActivity extends Activity implements
RecognitionListener {
boolean updateOn = false;
private static final int PERMISSIONS_FINE_LOCATION = 99;
TextView tv_lat, tv_lon, tv_add, tv_sen, tv_ud;
#SuppressLint("UseSwitchCompatOrMaterialCode")
Switch sw_locationupdates, sw_GPS;
LocationRequest locationRequest;
LocationCallback locationCallback;
FusedLocationProviderClient fusedLocationProviderClient;
/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";
private static final String STORE_SEARCH = "store";
private static final String LIBRARY_SEARCH = "library";
private static final String MUSEUM_SEARCH = "museum";
private static final String MENU_SEARCH = "menu";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "guide me";
/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
private SpeechRecognizer recognizer;
private TextToSpeech tts;
private HashMap<String, Integer> captions;
#SuppressLint("SetTextI18n")
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
// Prepare the data for UI
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_add = findViewById(R.id.tv_add);
sw_locationupdates = findViewById(R.id.sw_locationupdates);
tv_sen = findViewById(R.id.tv_sen);
sw_GPS = findViewById(R.id.sw_GPS);
tv_ud = findViewById(R.id.tv_ud);
captions = new HashMap<>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(LIBRARY_SEARCH, R.string.digits_caption);
captions.put(MUSEUM_SEARCH, R.string.phone_caption);
captions.put(STORE_SEARCH, R.string.forecast_caption);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// set properties of LocationRequest
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000 * 5);
locationRequest.setFastestInterval(1000 * 1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// triggered whenever update interval is met
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
updateUI(location);
}
};
sw_GPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_GPS.isChecked()) {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
tv_sen.setText("Using Tower + Wifi");
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
tv_sen.setText("Using GPS");
}
}
});
//StartLocUpdates();
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_locationupdates.isChecked()) {
//start tracking
StartLocUpdates();
} else {
//stop tracking
StopLocUpdates();
}
}
});
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new SetupTask(this).execute();
updateGPS();
}
private void StopLocUpdates() {
tv_lat.setText("Not tracking location");
tv_lon.setText("Not tracking location");
tv_add.setText("Not tracking location");
tv_ud.setText("Location stop tracking");
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
private void StartLocUpdates() {
//tv_ud.setText("stop ");
tv_ud.setText("Location is being tracked");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,null);
updateGPS();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//PERMISSIONS_REQUEST_RECORD_AUDIO
if (requestCode == PERMISSIONS_FINE_LOCATION || requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
updateGPS();
new SetupTask(this).execute();
} else {
Toast.makeText(this, "This app permission to be granted in order to work properly", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS() {
//get permission
//get current location
//update UI
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(PocketSphinxActivity.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//put values into UI
updateUI(location);
}
});
} else {
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private void updateUI(Location location) {
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(PocketSphinxActivity.this);
try{
List<Address>addresses=geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
tv_add.setText(addresses.get(0).getAddressLine(0));
}
catch(Exception e){
tv_add.setText("Unable to get address");
}
}
}
It seems that the location generated by fusedLocationProviderClient.getLastLocation() in method updateGPS() never changed. I wonder why.
private void updateGPS() {
//get permission
//get current location
//update UI
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(PocketSphinxActivity.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//put values into UI
updateUI(location);
}
});
} else {
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}

Unable to update TextView from location update

I'm just fetching the current location of the device and displaying on a TextView but the TextView does not show the results, however , it seems that the java code is fetching the location correctly but not updating the TextView as I have tried a lot relevant codes without error of location fetching.
Moreover, I am using a physical device to run the Application, not the emulator.
The recent code I've tried is as below:
public class roadSideSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener, LocationListener {
int MY_PERMISSION_LOCATION=100;
int MY_PERMISSION_ACCESS_COARSE_LOCATION=100;
protected LocationManager locationManager;
protected Context context;
TextView txtLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_side_selection);
marshmallowGPSPremissionCheck();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
txtLat = findViewById(R.id.latitudeTextview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = findViewById(R.id.latitudeTextview);
String s = getString(R.string.latitude, location.getLatitude(), location.getLongitude());
txtLat.setText(s);
}
#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");
}
private void marshmallowGPSPremissionCheck() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_LOCATION);
} else {
// gps functions.
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#Nullable String[] permissions,#Nullable int[] grantResults) {
if (requestCode == MY_PERMISSION_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
'''
Strings.xml
Latitude: %1$d; Longitude: %2$d
txtLat = (TextView) findViewById(R.id.latitudeTextview);
Cast the view to TextView and make sure you are using correct view id

How to show location permissions settings

How to show the location permission pop up with an allow and a deny button?
I have function that receives the location, but now I need to go to the settings by myself and turn the location on.
I want that when the User opens the fragment, the location pop up gets shown.
This is the code I currently have:
LocationFinder class:
public class LocationFinder extends Service implements LocationListener {
Context context;
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 200 * 10 * 1; // 2 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public LocationFinder(Context context) {
this.context = context;
getLocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
// Log.e("Network-GPS", "Disable");
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// Log.e("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
} else
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//Log.e("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Fragment that shows location:
public class GarageFragment extends Fragment {
LocationFinder finder;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_garage, container, false);
getLocation();
return view;
}
public void getLocation() {
double longitude = 0.0;
double latitude = 0.0;
finder = new LocationFinder(getContext());
if (finder.canGetLocation()) {
latitude = finder.getLatitude();
longitude = finder.getLongitude();
// Toast.makeText(getActivity(), "lat-lng " + latitude + "--" + longitude, Toast.LENGTH_LONG).show();
} else {
finder.showSettingsAlert();
}
Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
Toast.makeText(getActivity(), addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
} else {
// do your stuff
}
}
}
add this code to check your permission
if (ContextCompat.checkSelfPermission(Activity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(SplashActivity.this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(Activity.this, PERMISSIONS, 600);
} else {
// your code
}
add in your resultActivity
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.v("requestCode", "requestCode=" + requestCode);
switch (requestCode) {
case 600:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
case 700:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
}
}
Showing Location permission popup and turning location on are two different things.
You still have to go to setting to turn location on (if it's off), while permission is just allowing your app to use the location when it's on.
To get permission you can use this method RunTimePermissions.verifyStoragePermissions(getActivity());
public class RunTimePermissions {
// Storage Permissions variables
private static final int REQUEST_CODE = 6361;
private static String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
};
//persmission method.
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int locationPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
if (locationPermission != PackageManager.PERMISSION_GRANTED ) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS,
REQUEST_CODE
);
}
}
}
Add in manifests:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add in your activity:
public class MainActivity extends AppCompatActivity {
String[] locationPermissions= {"android.permission.ACCESS_COARSE_LOCATION","android.permission.ACCESS_FINE_LOCATION"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, locationPermissions, 121);
}
}
};
handler.postDelayed(runnable, 1000);
}
}

How to get the user's location using GPS

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" />

Categories

Resources