Annotations are not allowed here when moving to a separated class - android

I try to separate my Location finding code from the Main activity, so I moved the entire related code to a different class:
(*I began with Android today and Java is also fairly new to me, so sorry if this is a silly question)
public class LocationCode {
private LocationCallback mLocationCallback;
private TextView tv;
private Button button;
private FusedLocationProviderClient mFusedLocationClient;
private final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5;
public LocationCode (Context context, TextView textView, Button btn) {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
this.tv = textView;
this.button = btn;
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
Double latDouble = location.getLatitude();
String latString = latDouble.toString();
Double longtDouble = location.getLongitude();
String longtString = longtDouble.toString();
tv.setText(latString + " " + longtString);
}
}
};
#Override
public void onRequestPermissionsResult ( int requestCode,
String permissions[], int[] grantResults){
TextView tv1 = this.tv;
Button button = this.button;
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
tv1.setText("Not Granted!");
button.setVisibility(View.VISIBLE);
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
}
}
From MainActivity I should probably call this code like so:
LocationCode locationCode = new LocationCode(this, textView, Button);
But I get the following error on the second #Override (The one above public void onRequestPermissionsResult). Why is that, and how can I fix it? Or there is a better way to separate this code to make it look more neat in the MainActivity?

Related

Problem pausing the app while getting permission from user

I want to get location data but first I have to get permission from the user. so i want to pause the app while the user grants or denies the permission
this is how I tried to do it:
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final long LOCATION_REFRESH_TIME = 15000;
private static final float LOCATION_REFRESH_DISTANCE = 500;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
public Boolean locationPermissionResults=null;
double longitudeNetwork;
double latitudeNetwork;
TextView locationText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationText=findViewById(R.id.locationtext);
//getting the permission if its not granted
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) {
locationText.setText("give permission1");
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
//resume if granted
}
else{
locationManager();
}
}
private final LocationListener mLocationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
latitudeNetwork = location.getLatitude();
longitudeNetwork = location.getLongitude();
locationText.setText(Double.toString(longitudeNetwork) + "//" + Double.toString(latitudeNetwork));
}
};
#SuppressLint("MissingPermission")
public void locationManager(){
LocationManager locationManagerNetwork = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManagerNetwork.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListenerNetwork);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager();
} else{
locationText.setText("give permission2");
}
}
}
}
}
}
I have a problem with getting permission and handling the result. when the user denies the or grants the permission request the locationText shows give permission1 which means the moved over the first else in onCreate method and also the else in onRequestPermissionsResult.
why is this happening?
NOTE: in onRequestPermissionsResult I'm only checking for one of the permissions asked in onCreate because if one of them is granted the other one is granted too. can this be the problem?
You can't pause an app. Nor can you wait on the main thread. You need to reorganize your Activity so you don't need to do that- create an empty or waiting state that displays until that data is available.

How to gain permission to get GPS location in Android

I am new to Android and in my current project I am trying to retrieve location using GPS. The code for obtaining the location is in a separate non-activity class, because the fragment where I display the coordinates is crammed.
I have tried to use the guidelines from developer.android.com but I can't get any permission prompt, and when I press the button in the fragment, I only get the default 0-values for latitude and longitude.
I have provided the permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The GPS locator class:
public class LocationProvider implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int PERMISSION_REQUEST_LOCATION = 1;
private Activity activity;
Location gps_loc;
Location final_loc;
double longitude;
double latitude;
private LocationManager locationManager;
public LocationProvider(Activity activity) {
this.activity =activity;
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_LOCATION) {
// Request for permission.
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
requestLocationPermission();
}
}
}
private void getLocation() {
// Check if the permission has been granted
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gps_loc != null) {
Log.v("Loc_provider",gps_loc.toString());
final_loc = gps_loc;
latitude = final_loc.getLatitude();
longitude = final_loc.getLongitude();
}
} else {
requestLocationPermission();
}
}
private void requestLocationPermission() {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_LOCATION);
}
public String getCoordinates() {
return latitude + " "+ longitude;
}
}
The code in the fragment:
FloatingActionButton fab=view.findViewById(R.id.floatingActionButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locProvider=new LocationProvider(requireActivity());
gpsCoordinates.setText(locProvider.getCoordinates());
}
});
Tips and solutions for fixing the code are most welcome.
UPDATE 1:
I moved the code in the fragment instead, so that it looks like below:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkIfAlreadyhavePermission()) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
gpsCoordinates.setText(getCoordinates());
}
}
});
private String getCoordinates() {
if (gps_loc != null) {
Log.v("Loc_provider", gps_loc.toString());
final_loc = gps_loc;
latitude = gps_loc.getLatitude();
longitude = gps_loc.getLongitude();
}
return latitude + " " + longitude;
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Log.v("Grant_Results", String.valueOf(grantResults[0]));
Toast.makeText(getActivity(), "permission granted", Toast.LENGTH_LONG).show();
gpsCoordinates.setText(getCoordinates());
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I now get the permission prompt, but the location still doesn't update (I get 0).
Please note:
Saving an Activity object is not recommended this may cause memory leaks. Activity may be destroyed and recreated (for example when screen orientation changes). Holding a reference to the old activity will cause you problems.
Implementing the ActivityCompat.OnRequestPermissionsResultCallback interface does nothing. Your method will never be called. You will have to call it explicitly from the activity.
You have not requested permission, so your permission prompt will never be shown and the default value of double that is 0 will get returned. You need to call your getLocation() method so that the control falls on the else block and your permission prompt is shown
I recommend you handle permission in the activity. Have the activity get the coordinates for the location. You can have the activity implement an interface, say LocationFetcher, with a method getCoordinates(). You can then call this in the fragment like so:
LocationFetcher locationFetcher = (LocationFetcher) activity;
gpsCoordinates.setText(locationFetcher.getCoordinates());
Fixed by implementing LocationListener in Fragment and then adding
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
in onRequestPermissionsResult().

Problems with Google Location API

I am using a simple code and keep getting
java.lang.NullPointerException: Listener must not be null
I am only using a very short and simple code to try and get my current location, yet I can't get it to work. It might has to do something with that "null" at the looper place in the requestLocationUpdates callback. But I am not sure.
I've been trying all day already.
Here is the short code:
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private LocationCallback mLocationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
TextView tv = (TextView) findViewById(R.id.tv);
Double latDouble = location.getLatitude();
String latString = latDouble.toString();
tv.setText(latString);
}
};
};
}
All I want is to simply get current location, why is it giving me such hard times? What causes this error?
thanks
You're trying to use mLocationCallback before you initialise it. Just move this code :
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
TextView tv = (TextView) findViewById(R.id.tv);
Double latDouble = location.getLatitude();
String latString = latDouble.toString();
tv.setText(latString);
}
};
};
before this:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
The null in the Looper thread has nothing to do with it. By passing it as null you keep your callbacks on the calling thread.

Location Permission Not Switching on With Device

I have implemented location using FusedLocationProviderClient. The problem in my app is that the permission dialog does not switch on the location in settings. I have to manually turn it on before I start getting updates.
I have checked and requested permission using ContextCompat and ActivityCompat classes but nothing happens until I manually press the button. Is this a bug with FusedLocationProviderClient or bad programming on my side? I have worked with location manager and Fused Location Provider APIs and never faced this before.
Here's my code:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
private FusedLocationProviderClient providerClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
private static boolean isLocationGranted = false;
public static final int UPDATE_INTERVAL = 15000;
public static final int FASTEST_INTERVAL = 8000;
public static final int DISPLACEMENT = 10;
public static final int PLAY_SERVICES_REQ_CODE = 9009;
public static final int PLAY_SERVICES_RESOLUTION_REQ_CODE = 9090;
private SupportMapFragment mapFragment;
public HomeFragment() {
// Required empty public constructor
}
private void initViews(View view) {
toolbar = view.findViewById(R.id.toolbar);
driverStatusTV = view.findViewById(R.id.driverStatusTV);
statusSwitch = view.findViewById(R.id.statusSwitch);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
checkPerms();
providerClient = LocationServices.getFusedLocationProviderClient(getActivity());
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
driverStatusTV.setText("OFFLINE");
statusSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean b) {
if (b) {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Online", Snackbar.LENGTH_LONG).show();
if (checkPerms()) {
startLocationListener();
driverStatusTV.setText("ONLINE");
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
mGmap.setIndoorEnabled(false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGmap.setMyLocationEnabled(false);
stopLocationListener();
driverStatusTV.setText("OFFLINE");
if (currentMarker != null){
currentMarker.remove();
}
}
}
});
return view;
}
private void stopLocationListener() {
if (providerClient != null){
providerClient.removeLocationUpdates(locationCallback);
}
}
#Override
public void onPause() {
super.onPause();
stopLocationListener();
}
private void startLocationListener() {
locationRequest = LocationRequest.create();
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(getActivity());
client.checkLocationSettings(settingsRequest);
displayLocation();
}
private boolean checkPerms() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
isLocationGranted = false;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
} else {
isLocationGranted = true;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
}
return isLocationGranted;
}
private void reqPerms() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
if (statusSwitch.isChecked()) {
providerClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
mGmap.setIndoorEnabled(true);
mGmap.setMyLocationEnabled(true);
} else {
mGmap.setIndoorEnabled(false);
mGmap.setMyLocationEnabled(false);
}
}
}
private LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
mLastLocation = location;
if (currentMarker != null) {
currentMarker.remove();
}
latitude = mLastLocation.getLatitude();
Log.d(TAG, "Lat:\t" + latitude);
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Long:\t" + longitude);
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(latitude, longitude));
options.title("Driver");
//options.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)); // throws error
currentMarker = mGmap.addMarker(options);
rotateMarker(currentMarker, 360, mGmap);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 18.0f));
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isLocationGranted = true;
if (checkPlayServices() && statusSwitch.isChecked()) {
startLocationListener();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), AppConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Play Services NOT Supported on Your Device", Snackbar.LENGTH_LONG).show();
getActivity().finish();
getActivity().moveTaskToBack(true);
}
return false;
}
return true;
}
private void rotateMarker(final Marker currentMarker, final float i, GoogleMap mGmap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = currentMarker.getRotation();
final int duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.postDelayed(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.elapsedRealtime() - start;
float t = interpolator.getInterpolation(elapsed / duration);
float rot = t * i + (1 - t) * startRotation;
currentMarker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
}, duration);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
startLocationListener();
}
}
Alos, the set icon on marker throws this error com.google.maps.api.android.lib6.common.apiexception.b: Failed to decode image. The provided image must be a Bitmap.
Can anyone help me solve these two problems? Thank you
your onRequestPermissionsResult will never be called, you are requesting permissions from your activity and your activity's onRequestPermissionsResult would be getting invoked. If you want permission callback in your fragment just remove Activity when you request permssions
private void reqPerms() {
requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
Your fragment has to be a supportFragment if you want to access this method

Calculate Moving Speed of USER in android studio

I need to calculate Speed with which the user is moving. So we need two things to calculate speed which are GPS and Accelerometer.
But both have their limitations.
GPS is not available all the time.While I getting the current
location of user always I am getting from Network provider only and
not from GPS.
Accelerometer is not accurate.
So which approach should I go with?
Accelerometer is not reliable , for now you can try testing, and tweaking stuff to meet your requirements.
Check here:
https://github.com/bagilevi/android-pedometer
One of many features:
calculate distance and speed based on user’s step length
Please try the below way of getting the speed of moving using the GPS
public class MainActivity extends AppCompatActivity {
TextView textView;
private FusedLocationProviderClient mFusedLocationClient;
private double lat;
private double lng;
private static int UPDATE_INTERVAL = 1000;
private static int FATEST_INTERVAL = 1000;
private static int DISPLACEMENT = 0;
private double speed = 0.0;
double currentSpeed,kmphSpeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
#Override
protected void onResume() {
super.onResume();
if (!runtime_permissions()) {
requestLocations();
}
}
#Override
protected void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
private void requestLocations() {
LocationRequest mLocationRequest = new LocationRequest();
// mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Location location2 = locationResult.getLastLocation();
lat = location.getLatitude();
lng = location.getLongitude();
speed = location.getSpeed();
currentSpeed = round(speed,3,BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
//speed in km/h
// speed = (int) ((location.getSpeed() * 3600) / 1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("speed=== "+speed+"\ncurrentspeed==="+currentSpeed+"\nkmph speed === "+kmphSpeed);
}
});
// Log.i("SensorTestActivity","SPEEDDDDDspeed=== "+speed+" ");
}
}
};
public static double round(double unrounded, int precision, int roundingMode) {
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
private boolean runtime_permissions() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onResume();
} else {
runtime_permissions();
}
}
}
}

Categories

Resources