Related
I am trying to get current location using FusedLocationAPI in my application. It works just fine in both android API>23 and <23. The issue is in case of GPS is not enabled, the app prompts the user to enable the GPS and after that the location returns null. But while restarting the app, it works just fine. In case of GPS not being turned OFF, the app just works fine. Is there any way that the app can wait for the GPS to be enabled before getting the location? below I am posting my code. Please have a look.
Inside onCreate():
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
displayPromptForEnablingGPS(this);
}
Log.d("permipart", "before");
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
else {
RequestMultiplePermission();
}
if(Build.VERSION.SDK_INT<= 23)
{
buildGoogleApiClient();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
Log.d("permipart", "out");
Other methods:
#Override
public void onLocationChanged(Location location) {
Log.d("onconnectedlocchange","called");
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
if (!String.valueOf(lat).equals("0.0"))
{
latitudeVal = location.getLatitude();
longitudeVal = location.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
// If, If permission is not enabled then else condition will execute.
else {
//Calling method to enable permission.
RequestMultiplePermission();
}
Log.d("onconnected","called");
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Update location every second
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
else
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
if (!String.valueOf(lat).equals("0.0")){
latitudeVal = mLastLocation.getLatitude();
longitudeVal = mLastLocation.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal)+ longitudeVal);
}
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void displayPromptForEnablingGPS(final Activity activity) {
final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Do you want open GPS setting?";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
String[] permissions = new String[]{ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
//Permission function starts from here
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
Log.d("permipart", "RequestMultiplePermission");
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE,
ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION
}, RequestPermissionCode);
}
private boolean checkPermission() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(this,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),10 );
Log.d("permissionissue","no");
return false;
}
Log.d("permissionissue","yes");
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("permipart", "onRequestPermissionsResult");
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean RecordAudioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean SendSMSPermission = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean GetAccountsPermission = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (CameraPermission && RecordAudioPermission && SendSMSPermission && GetAccountsPermission) {
Log.d("permipart", "done");
buildGoogleApiClient();
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
/**
* Checking permission is enabled or not using function starts from here.
*
*/
public boolean CheckingPermissionIsEnabledOrNot() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int ForthPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_COARSE_LOCATION);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
SecondPermissionResult == PackageManager.PERMISSION_GRANTED &&
ThirdPermissionResult == PackageManager.PERMISSION_GRANTED &&
ForthPermissionResult == PackageManager.PERMISSION_GRANTED ;
}
You need to recieve the broadcast of the GPS status something like this:
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// here you can get the location or start a service to get it.
// example
// Intent getLocationService = new Intent(context,YourService.class);
// context.startService(getLocationService);
}
}
}
update
according to comment below
use this in your code
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(manager.isProviderEnabled( LocationManager.GPS_PROVIDER)){
// it is enabled
}else{
// it is not
}
Use my code, it will ask the user to turn on GPS if it is turned off. It will never return you anything until GPS turned on.
Note: you have to get location permission before using it for marshmallow and above mobiles.
Try this:
#SuppressWarnings("MissingPermission")
public class LocationFinder implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String TAG = "LocationFinder";
private static final String BROADCAST_GPS_REQ = "LocationFinder.GPS_REQ";
private static final String KEY_GPS_REQ = "key.gps.req";
private static final int GPS_REQUEST = 2301;
private Activity activity;
private FinderType finderType;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private long updateInterval;
private long fastestInterval;
private GpsRequestListener gpsRequestListener;
private LocationUpdateListener locationUpdateListener;
public LocationFinder(Activity activity, FinderType finderType) {
this.activity = activity;
this.finderType = finderType;
}
private void connectGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
private void createLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(updateInterval);
locationRequest.setFastestInterval(fastestInterval);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int intExtra = intent.getIntExtra(KEY_GPS_REQ, 0);
switch (intExtra) {
case Activity.RESULT_OK:
try {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
} catch (Exception e) {
e.printStackTrace();
}
gpsRequestListener.gpsTurnedOn();
break;
case Activity.RESULT_CANCELED:
gpsRequestListener.gpsNotTurnedOn();
}
}
};
public void gpsRequestCallback(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
LocalBroadcastManager.getInstance(activity).registerReceiver(receiver, new IntentFilter(BROADCAST_GPS_REQ));
}
public void config(long updateInterval, long fastestInterval) {
this.updateInterval = updateInterval;
this.fastestInterval = fastestInterval;
}
public void find(LocationUpdateListener listener) {
this.locationUpdateListener = listener;
createLocationRequest();
connectGoogleApiClient();
}
private void find() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(activity, GPS_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d(TAG, "No GPS Hardware");
break;
}
}
});
}
public void stopFinder() {
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
try {
activity.unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "GoogleApiClient: Connected");
find();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "GoogleApiClient: onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApiClient: onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
if (finderType != FinderType.TRACK)
stopFinder();
locationUpdateListener.onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
}
public void setGpsRequestListener(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
}
public static void onRequestResult(Activity activity, int requestCode, int resultCode) {
if (requestCode == GPS_REQUEST) {
Intent intent = new Intent(BROADCAST_GPS_REQ);
intent.putExtra(KEY_GPS_REQ, resultCode);
LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
}
}
public enum FinderType {
// It will update the current GPS location once.
GPS,
//It will update the user location continuously.
TRACK
}
public interface LocationUpdateListener {
void onLocationUpdate(LatLng latLng);
}
public interface GpsRequestListener {
void gpsTurnedOn();
void gpsNotTurnedOn();
}
}
To get location update initialize the class like this:
public class MyActivity extends AppCompatActivity implements
LocationFinder.GpsRequestListener,
LocationFinder.LocationUpdateListener {
private LocationFinder locationUpdater;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationUpdater = new LocationFinder(this, LocationFinder.FinderType.TRACK);
driverLocationUpdater.gpsRequestCallback(this);
driverLocationUpdater.config(5000, 5000);
driverLocationUpdater.find(this);
}
#Override
protected void onDestroy(){
super.onDestroy()
driverLocationUpdater.stopFinder();
}
#Override
public void onLocationUpdate(LatLng latLng) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LocationFinder.onRequestResult(this, requestCode, resultCode);
}
}
I'm trying to get latitude and longitude from Android device and send it to MySQL database. when any one register his current latitude and longitude saved in the database.but i want to know that how to update saved latitude and longitude in every 10 seconds.here is my code:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, GoogleMap.OnCameraMoveListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
mGoogleMap.clear();
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mCurrLocationMarker.setPosition(latLng);
CameraPosition liberty = CameraPosition.builder().target(new LatLng(latitude, longitude)).zoom(15.5f).bearing(0).tilt(45).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
Intent intent = new Intent(MainActivity.this, Register.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
callAsynchronousTask();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onCameraMove() {
mCurrLocationMarker.setPosition(mGoogleMap.getCameraPosition().target);
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Register performBackgroundTask = new Register();
performBackgroundTask.onSupportContentChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000);
}
}
Register class:-
public class Register extends AppCompatActivity {
EditText name_txt, email_txt, mobile_txt;
String getname, getemail, getmobilenumber;
Button upload, register;
TextView image_text;
TypedFile avatarFile1 = null;
String picturePath = "";
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
File uri;
double getlatitude;
double getlongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Find_view_by_id();
Bundle extras = getIntent().getExtras();
getlatitude = extras.getDouble("Latitude");
getlongitude = extras.getDouble("Longitude");
Toast.makeText(this, "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, Toast.LENGTH_SHORT).show();
}
private void Find_view_by_id() {
name_txt = (EditText) findViewById(R.id.name);
email_txt = (EditText) findViewById(R.id.email);
mobile_txt = (EditText) findViewById(R.id.mobilenumber);
upload = (Button) findViewById(R.id.upload_image);
image_text = (TextView) findViewById(R.id.upload_image_text);
register = (Button) findViewById(R.id.register);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getname = name_txt.getText().toString();
getemail = email_txt.getText().toString();
getmobilenumber = mobile_txt.getText().toString();
if (getname.trim().equalsIgnoreCase("")) {
name_txt.setError("Please Enter First Name");
name_txt.requestFocus();
} else if (getemail.trim().equalsIgnoreCase("")) {
email_txt.setError("Please Enter email address");
email_txt.requestFocus();
} else if (!getemail.matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+")) {
email_txt.setError("Please Enter valid email address");
email_txt.requestFocus();
} else if (getmobilenumber.trim().equalsIgnoreCase("")) {
mobile_txt.setError("Please enter mobile number");
mobile_txt.requestFocus();
} else if (getmobilenumber.length() < 10) {
mobile_txt.setError("Please Enter correct mobile number");
mobile_txt.requestFocus();
} else {
Register_user(getname, getemail, getmobilenumber, picturePath, getlatitude, getlongitude);
}
}
private void Register_user(String name, String email, String mobilenumber, String avatarFile, Double latitud_e, Double longitud_e) {
if (avatarFile != null) {
avatarFile1 = new TypedFile("image/*", new File(String.valueOf(avatarFile)));
}
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constant.constant).build();
Register_API registerapi = restAdapter.create(Register_API.class);
registerapi.getuser(name, email, mobilenumber, avatarFile1, latitud_e, longitud_e, new Callback<RegisterModel>() {
#Override
public void success(RegisterModel registerModel, Response response) {
Long status = registerModel.getSuccess();
if (status == 1) {
name_txt.setText("");
email_txt.setText("");
mobile_txt.setText("");
image_text.setText("");
Toast.makeText(Register.this, "Successful ", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Register.this, Show_List_Activity.class);
startActivity(i);
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(Register.this, "Failure ", Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Take Photo"))
cameraIntent();
else if (userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
Log.e("log path", "" + uri);
String myImagename = getImageName(String.valueOf(uri));
image_text.setText(myImagename);
}
}
}
private String getImageName(String picturePath) {
String Imagename = null;
String[] name_array = picturePath.split("/");
Log.e("size of array", "" + name_array.length);
Imagename = name_array[name_array.length - 1];
Log.e("name of image", "" + Imagename);
return Imagename;
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(Register.this);
if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
uri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CAMERA);
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/.Dope/");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
File mediaFile;
java.util.Date date = new java.util.Date();
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir, Long.toString(System.currentTimeMillis()) + "IMG_" + new Timestamp(date.getTime()).toString() + ".jpg");
} else {
return null;
}
return mediaFile;
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
String myimagename = getImageName(picturePath);
image_text.setText(myimagename);
}
}
}
You have to use threads for this purpose , with time out of 10 seconds so every 10 seconds your code in thread will run
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// insert your data to db here
// close this activity
finish();
}
}, TIME_OUT);
And set time out as
private static int TIME_OUT = 10000;
Here you go :)
Create a background service class like this
public class LocationBackGroundService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationBackGroundService";
private static final long INTERVAL = 100;
private static final long FASTEST_INTERVAL = 100;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
Context mCOntext;
public void LocationBackGroundService(Context mContext) {
this.mCOntext = mContext;
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Override
public void onCreate() {
super.onCreate();
if (!isGooglePlayServicesAvailable()) {
// finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
return false;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "OnConnection Suspended", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "OnConnection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (null != mCurrentLocation) {
mCurrentLocation = location;
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
}
}
}
And call when activity starts like this
startService(new Intent(this, yourBackgroundServiceName.class));
and in menifest
<service android:name=".yourBackgroundServiceName"></service>
and don;t forget to add run time permissions before stating a service
Instead saving your lat lon to LocalDB you can use Shared Preferences.
For more help about shared Preferences use given link https://www.tutorialspoint.com/android/android_shared_preferences.htm
Make different class and make a method to save your lat lon when ever you get after 10 second.
THanks!
In my app I want to fetch Latitude, Longitude and current Location name and pass this value in the database. The app is running perfectly in Tab. But in case of other device getLastKnownLocation() returns null. For this reason I am facing nullpointerexception.
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Location l = locationmanager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
Please help me to solve this. I know this issue is asked before. But I have tried most of them. Still I am facing the nullpointerexception in the same place(while fetching lat long value).
10-13 15:54:12.825 16095-16095/com.example.ivdisplays.vehereapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ivdisplays.vehereapp, PID: 16095
java.lang.NullPointerException
at com.example.ivdisplays.vehereapp.MainActivity$1.onClick(MainActivity.java:117)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18792)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5344)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:676)
at dalvik.system.NativeStart.main(Native Method)
public class MainActivity extends AppCompatActivity implements NetworkCallback,
LocationListener {
private EditText empIdTxt;
private EditText passwordTxt;
private TextView tv_lat;
private TextView tv_long;
private TextView tv_place;
private Button loginBtn;
private Button logoutBtn;
LocationManager locationmanager;
GPSTracker gps;
String cityName = "";
Context context;
static String loginDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
empIdTxt = (EditText) findViewById(R.id.et_loginId);
passwordTxt = (EditText) findViewById(R.id.et_loginPass);
loginBtn = (Button) findViewById(R.id.bt_login);
logoutBtn= (Button) findViewById(R.id.bt_logout);
empIdTxt.addTextChangedListener(new MyTextWatcher(empIdTxt));
passwordTxt.addTextChangedListener(new MyTextWatcher(passwordTxt));
empIdTxt.setText("vinay");
passwordTxt.setText("qwerty");
context=MainActivity.this;
final Location location = getLastKnownLocation();
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_LONG).show();
System.out.println("Output of Location is:" + getLastKnownLocation());
}
loginDate = AlertDialogManager.todayDate();
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validateEmpID()) {
return;
}
if (!validatePassword()) {
return;
}
LoginApi api = new LoginApi(context, (NetworkCallback) context);
System.out.println("Output of LoginAPI:" +"username" +empIdTxt.getText().toString()
+"password"+passwordTxt.getText().toString()+"Lat"+location.getLatitude()+"Long"+location.getLongitude()
+"Date"+loginDate+"Locality"+new GPSTracker(MainActivity.this).getLocality(location));
api.processLogin(empIdTxt.getText().toString(), passwordTxt.getText().toString(),
location.getLatitude()+"",location.getLongitude()+"",loginDate,
new GPSTracker(MainActivity.this).getLocality(location),"123456");
loginBtn.setVisibility(View.GONE);
logoutBtn.setVisibility(View.VISIBLE);
}
});
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LogoutApi api = new LogoutApi(context, (NetworkCallback) context);
System.out.println("Output of LogoutAPI:" +"userid " +AppDelegate.getInstance().uid
+"Lat"+location.getLatitude()+"Long"+location.getLongitude()
+"Date"+AlertDialogManager.todayDate()+"Locality"+new GPSTracker(MainActivity.this).getLocality(location));
api.processLogout(AppDelegate.getInstance().uid,
location.getLatitude()+"",location.getLongitude()+"",AlertDialogManager.todayDate(),
new GPSTracker(MainActivity.this).getLocality(location),"123456","");
logoutBtn.setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
}
});
}
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Location l = locationmanager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private boolean validateEmpID() {
if (empIdTxt.getText().toString().trim().isEmpty()) {
empIdTxt.setError(ErrorUtil.USERNAME_ERROR);
requestFocus(empIdTxt);
return false;
}
return true;
}
private boolean validatePassword() {
if (passwordTxt.getText().toString().trim().isEmpty()) {
passwordTxt.setError(ErrorUtil.PASSWORD_ERROR);
requestFocus(passwordTxt);
return false;
}
return true;
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.et_loginId:
validateEmpID();
break;
case R.id.et_loginPass:
validatePassword();
break;
}
}
}
#Override
public void updateScreen(String data, String tag) {
if (tag.compareTo(ApiUtil.TAG_LOGIN) == 0) {
try {
System.out.println("Login Response"+data);
JSONObject mainObj = new JSONObject(data);
AppDelegate ctrl = AppDelegate.getInstance();
if (!mainObj.isNull("user_id")) {
ctrl.uid = mainObj.getString("user_id");
}
if (!mainObj.isNull("error")) {
Toast.makeText(MainActivity.this,"Login Fails",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show();
}
}
if (tag.compareTo(ApiUtil.TAG_LOGOUT) == 0) {
try {
System.out.println("Logout Response"+data);
JSONObject mainObj = new JSONObject(data);
AppDelegate ctrl = AppDelegate.getInstance();
if (!mainObj.isNull("message")) {
Toast.makeText(MainActivity.this,"Logout Success",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Logout Fails",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onLocationChanged(Location location) {
double latitude,longitude;
tv_lat = (TextView) findViewById(R.id.tv_lat);
tv_long = (TextView) findViewById(R.id.tv_long);
tv_place = (TextView) findViewById(R.id.tv_place);
latitude=location.getLatitude();
longitude=location.getLongitude();
tv_lat.setText("Latitude : "+latitude);
tv_long.setText("Longitude : "+ longitude);
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude,
longitude, 1);
System.out.println("Output of Address" + addresses);
cityName = addresses.get(0).getAddressLine(0);
System.out.println("Cityname is" + cityName);
tv_place.setText("Place : "+cityName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I think the problem is about checking permissions and && != operands. Handle it more carefully.
Try this:
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
boolean permissionsActivated = canAll();
if (!permissionsActivated)
return null;
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// this may lead to 'null' value if not permissions
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
private boolean canAll() {
// TODO Auto-generated method stub
return (canAccessLocation() && canCoarseLocation());
}
private boolean canAccessLocation() {
return hasPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
private boolean canCoarseLocation() {
return hasPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
#SuppressLint("NewApi")
private boolean hasPermission(String perm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (PackageManager.PERMISSION_GRANTED == checkSelfPermission(perm));
} else {
return true;
}
}
Do not forget:
getLastKnownLocation may return a null value if the application has not detected any location.
You can use GoogleApiClient's fused location provider for fetching location. You need to add a dependency in your gradle file. i.e
compile 'com.google.android.gms:play-services-location:9.6.1'
Add fine_location permission needed in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It is a Dangerous Permission you need to ask permission at runtime like this.
Code Snippet
public class DashboardActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
ResultCallback<LocationSettingsResult> {
private GoogleApiClient googleApiClient;
private GoogleApiAvailability apiAvailability;
private static final long MIN_TIME_BW_UPDATES = 10000;
private static final long FAST_TIME_BW_UPDATES = 3000;
private final static int REQUEST_CHECK_SETTINGS = 100;
private static final long EXPIRATION_DURATION = 3600000;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;
private Location location;
private LatLng latLng = new LatLng(0, 0);
private double latitude;
private double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
init();
}
private void init() {
apiAvailability = GoogleApiAvailability.getInstance();
if (googleApiAvaibility()) {
buildGoogleApiClient();
displayLocation();
}
}
protected void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(MIN_TIME_BW_UPDATES);
mLocationRequest.setFastestInterval(FAST_TIME_BW_UPDATES);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setExpirationDuration(EXPIRATION_DURATION);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean googleApiAvaibility() {
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
switch (resultCode) {
case ConnectionResult.SUCCESS:
return true;
case ConnectionResult.API_UNAVAILABLE:
Dialog dialog = apiAvailability.getErrorDialog(this, ConnectionResult.API_UNAVAILABLE, 200,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//finish();
}
});
dialog.show();
break;
case ConnectionResult.SERVICE_MISSING:
Dialog dialog1 = apiAvailability.getErrorDialog(this, ConnectionResult.SERVICE_MISSING, 201,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//finish();
}
});
dialog1.show();
break;
}
return false;
}
#Override
public void onLocationChanged(Location location) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
//here you will get new latitude and longitude if location is changed
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
displayLocation();
break;
case Activity.RESULT_CANCELED:
//finish();
Toast.makeText(getActivity(), "Please enable location. Otherwise you can not use this application", Toast.LENGTH_LONG).show();
break;
}
break;
default:
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
createLocationRequest();
checkLocationSettings();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
googleApiClient.connect();
}
#Override
public void onResult(#NonNull LocationSettingsResult result) {
Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
displayLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.e("Exception", e.toString());
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//showDialog(this,"You have choose never for Location!");
break;
default:
break;
}
}
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.
checkLocationSettings(googleApiClient, mLocationSettingsRequest);
result.setResultCallback(this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 250);
} else {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
//print latitude longitude here
} else {
if (googleApiAvaibility()) {
buildGoogleApiClient();
googleApiClient.connect();
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
if (location != null) {
displayLocation();
} else {
//googleApiClient.connect();
if (googleApiAvaibility()) {
buildGoogleApiClient();
googleApiClient.connect();
}
}
}
}
}
}
You can also check this sample
I want to implement a service that will show the loading screen till the GPS dont find location in it. After some time it shows alert and return the place last known location or the basic cord (0.0). Unfortunatly the first read is null and it stays like this no matter if the GPS is on or off.
GPS HANDLER
public class GPSLocation implements ConnectionCallbacks,OnConnectionFailedListener,
LocationListener,
GPSStatusReceiver.GpsStatusChangeListener{
public static final int REQUEST_CHECK_SETTINGS = 100;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 200;
private static final int PERMISSION_GRANTED = 0;
private static final int PERMISSION_DENIED = 1;
private static final int PERMISSION_BLOCKED = 2;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private LocationCallback mCallback;
private Activity mActivity;
private Context mContext;
private LocationRequest mLocationRequest;
private GPSStatusReceiver mGPSStatusReceiver;
private long intervalMillis = 10000;
private long fastestIntervalMillis = 5000;
private int accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;
private boolean isInitialized = false;
private boolean isLocationEnabled = false;
private boolean isPermissionLocked = false;
public GPSLocation(Activity activity, LocationCallback callback) {
mActivity = activity;
mContext = activity.getApplicationContext();
mCallback = callback;
//creating new client Api
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGPSStatusReceiver = new GPSStatusReceiver(mContext, this);
}
public void init(){
isInitialized = true;
if(mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
requestPermission();
} else {
connect();
}
}
}
public void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(intervalMillis);
mLocationRequest.setFastestInterval(fastestIntervalMillis);
mLocationRequest.setPriority(accuracy);
}
public LocationRequest getLocationRequest() {
return mLocationRequest;
}
public void connect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.connect();
}
}
public void disconnect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.disconnect();
}
}
private void getLastKnownLocation(){
if(!mGoogleApiClient.isConnected()){
Log.i(TAG, "getLastKnownLocation restart ");
mGoogleApiClient.connect();
}
else {
if (checkLocationPermission(mContext) && isLocationEnabled) {
Log.i(TAG, "getLastKnownLocation read ");
if(mCurrentLocation==null){
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mCallback.onLastKnowLocationFetch(mCurrentLocation);
Log.i(TAG,"mCurrentLocation is "+mCurrentLocation);
}
startLocationUpdates();
}else{
Log.i(TAG, "getLastKnownLocation get permission ");
requestPermission();
}
}
Log.i(TAG, "mCurrentLocation " + mCurrentLocation);
}
public void startLocationUpdates() {
if(checkLocationPermission(mContext)
&& mGoogleApiClient != null
&& mGoogleApiClient.isConnected()
&& isLocationEnabled) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
public void stopLocationUpdates() {
if(mGoogleApiClient != null
&& mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (checkLocationPermission(mContext) && isLocationEnabled) {
Log.i(TAG, "getLastKnownLocation read ");
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
if(mCurrentLocation == null ) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mCallback.onLastKnowLocationFetch(mCurrentLocation);
}
startLocationUpdates();
}
Log.i(TAG, "onConnected");
mCallback.onLocationUpdate(mCurrentLocation);
requestPermission();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged : " + location);
if(location!=null)
mCallback.onLocationUpdate(location);
}
#Override
public void onGpsStatusChange() {
Log.i(TAG, "onGpsStatusChange");
if(isInitialized && !isPermissionLocked) {
if (!isLocationEnabled(mContext)) {
isLocationEnabled = false;
isPermissionLocked = true;
stopLocationUpdates();
requestPermission();
}
}
}
private void requestPermission(){
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
String[] appPerm = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(mActivity, appPerm, LOCATION_PERMISSION_REQUEST_CODE);
}else{
getLocationSetting();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
if (resultCode == Activity.RESULT_OK) {
getLastKnownLocation();
}else{
Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
}
}
}
private void getLocationSetting(){
LocationSettingsRequest.Builder builder =
new LocationSettingsRequest
.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "SUCCESS");
isLocationEnabled = true;
isPermissionLocked = false;
getLastKnownLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "RESOLUTION_REQUIRED");
try {
status.startResolutionForResult(
mActivity,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
mCallback.onLocationSettingsError();
}finally {
isPermissionLocked = false;
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "SETTINGS_CHANGE_UNAVAILABLE");
Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
isPermissionLocked = false;
break;
}
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permState;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(
mActivity,
Manifest.permission.ACCESS_FINE_LOCATION)){
permState = PERMISSION_BLOCKED;
}else{permState = PERMISSION_DENIED;}
}else {permState = PERMISSION_GRANTED;}
}
else{permState = PERMISSION_DENIED;}
switch (permState){
case PERMISSION_BLOCKED:
Toast.makeText(mContext,"Please give gps location permission to use the app.",Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity(mContext);
mCallback.onLocationPermissionDenied();
break;
case PERMISSION_DENIED:
Toast.makeText(mContext,"Permission Denied, app cannot access the gps location.", Toast.LENGTH_LONG).show();
break;
case PERMISSION_GRANTED:
getLocationSetting();
break;
}
break;
}
}
public static boolean isLocationEnabled(Context context){
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = false;
boolean networkEnabled = false;
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
return gpsEnabled && networkEnabled;
}
public static void startInstalledAppDetailsActivity(final Context context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
public static boolean checkLocationPermission(Context context) {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
public interface LocationCallback {
void onLastKnowLocationFetch(Location location);
void onLocationUpdate(Location location);
void onLocationPermissionDenied();
void onLocationSettingsError();
}
public void close() {
mGPSStatusReceiver.unRegisterReceiver();
}}
Recivier Class
public class GPSStatusReceiver extends BroadcastReceiver {
private GpsStatusChangeListener mCallback;
private Context mContext;
public GPSStatusReceiver(Context context, GpsStatusChangeListener callback) {
mCallback = callback;
mContext = context;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.location.PROVIDERS_CHANGED");
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
context.registerReceiver(this, intentFilter);
}
public void unRegisterReceiver(){
Log.i(TAG, "unRegisterReceiver");
mContext.unregisterReceiver(this);
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.i(TAG, "in PROVIDERS_CHANGED");
mCallback.onGpsStatusChange();
}
}
public interface GpsStatusChangeListener{
void onGpsStatusChange();
}}
Activity Class
public class LocationFinder extends AppCompatActivity implements GPSLocation.LocationCallback,OnMapReadyCallback {
Log log;
private GoogleMap mMap;
Button confirmLocalizationButton;
private GPSLocation mGPSLocation;
private LatLng currentPosition= new LatLng(0,0);
MarkerOptions markerOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGPSLocation = new GPSLocation(this, this);
mGPSLocation.init();
mapInit();
buttonInit();
checkInternetStatus();
}
private void buttonInit() {
confirmLocalizationButton = (Button)findViewById(R.id.confirm_location);
confirmLocalizationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPosition=markerOptions.getPosition();
log.i(TAG,"currentPosition:: "+currentPosition);
Intent i = new Intent(LocationFinder.this,MainActivity.class);
i.putExtra("coordinates",currentPosition);
startActivity(i);
finish();
}
});
}
#Override
public void onLastKnowLocationFetch(Location location) {
if(location != null) {
Log.i(TAG, "onLastKnowLocationFetch " + location);
}
}
#Override
public void onLocationUpdate(Location location) {
if(location != null) {
Log.i(TAG, "onLocationUpdate " + location);
}
}
#Override
public void onLocationPermissionDenied() {
}
#Override
public void onLocationSettingsError() {
}
#Override
protected void onStart() {
mGPSLocation.connect();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mGPSLocation.startLocationUpdates();
}
#Override
protected void onPause() {
super.onPause();
mGPSLocation.stopLocationUpdates();
}
#Override
protected void onStop() {
mGPSLocation.disconnect();
super.onStop();
}
#Override
protected void onDestroy() {
mGPSLocation.close();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE) {
mGPSLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
mGPSLocation.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(currentPosition, 1);
mMap.moveCamera(camera);
markerOptions = new MarkerOptions()
.position(currentPosition);
mMap.addMarker(markerOptions);
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
markerOptions = new MarkerOptions().position(mMap.getCameraPosition().target);
mMap.clear();
mMap.addMarker(markerOptions);
}
});
}
private void mapInit(){
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void checkInternetStatus(){
if(!InternetConnection.getConnectivityStatus(this)) {
new android.app.AlertDialog.Builder(this)
.setMessage("Turn on your network service to enjoy full functionality of this application ")
.setCancelable(true).
setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
}
UPDATE: Ive made function that will wait for GPS signal but still does make a connection
private void waitForGPSSignal(){
progressWindow();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getLastKnownLocation();
if(mCurrentLocation!=null)
progress.dismiss();
}
}, 10000);
}
ProgressDialog progress;
private void progressWindow() {
progress = new ProgressDialog(mContext);
progress.setMessage("waiting");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
if (mContext != null) {
progress.show();
}}
I called it for GPSLocation in here:
result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "SUCCESS");
isLocationEnabled = true;
isPermissionLocked = false;
waitForGPSSignal();
getLastKnownLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "RESOLUTION_REQUIRED");
try {
status.startResolutionForResult(
mActivity,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
mCallback.onLocationSettingsError();
}finally {
isPermissionLocked = false;
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "SETTINGS_CHANGE_UNAVAILABLE");
Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
isPermissionLocked = false;
break;
}
}
});
And Im still obtain null.
Here is what you can do.
if (Utility.isLocationEnabled(Splash_Activity.this)) {
new FetchCordinates.execute();
} else {
buildAlertMessageNoGps();
}
FetchCordinates.java
public class FetchCordinates extends AsyncTask<String, Integer, String> {
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(InitialRegistration.this, "",
"Fetching Location");
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
// Log.e("AsynckLL", "LATITUDE :" + mLatitude + " LONGITUDE :"
// + mLongitude);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
// do your logic
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected String doInBackground(String... params) {
while (mLatitude == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// Log.e("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
// Log.e("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// Log.e("onStatusChanged", "onStatusChanged");
}
}
}
if Location is not enabled.
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(
Splash_Activity.this);
builder.setMessage(
"Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
100);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
and inside onActivityResults
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (Utility.isLocationEnabled(Splash_Activity.this)) {
new FetchCordinates().execute();
} else {
buildAlertMessageNoGps();
}
} else {
Toast.makeText(getApplicationContext(), "Location Off", 1000)
.show();
}
}
This is not service as you mentioned in your question. but i hope somehow it will help you.
Happy Coding.
I want to check if the GPS is on if it is should show the current location. If not it should ask to turn it on. If user click cancel or dont turn the coordinates will be set as basic. Unfortunetly allways choose the basic. Even if the GPS is of (i dont get the message to turn on GPS)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManagerr = (LocationManager) getSystemService(LOCATION_SERVICE);
currentLocation=new Location("location");
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
getLocation();
log.i(TAG,"latitude "+currentLocation.getLatitude());
}
private Location getLocation(){
locationListener= new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentLocation=location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LocationFinder.this);
alertDialogBuilder.setMessage("GPS is off. Want to turn on GPS?")
.setCancelable(false)
.setPositiveButton("Turn On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
currentLocation=setStartCoordinate();
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
};
return currentLocation;
}
private Location setStartCoordinate(){
Location primaryLocalization= new Location("Basic");
primaryLocalization.setLongitude(0);
primaryLocalization.setLatitude(0);
return primaryLocalization;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
try{
getLocation();
log.i(TAG,"latitude "+currentLocation.getLatitude());
}
catch (SecurityException ex){log.i(TAG,"security error");}
break;
default:
break;
}
}
This requires a lot of case handling and I am providing a complete implementation of the all the features you requested with brief explanations below.
1. Provide location permission in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2. Add location dependency in app's build.gradle
compile 'com.google.android.gms:play-services-location:9.2.1'
3. extend BroadcastReceiver and create GPSStatusReceiver
public class GPSStatusReceiver extends BroadcastReceiver {
private GpsStatusChangeListener mCallback;
private Context mContext;
public GPSStatusReceiver(Context context, GpsStatusChangeListener callback) {
mCallback = callback;
mContext = context;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.location.PROVIDERS_CHANGED");
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
context.registerReceiver(this, intentFilter);
}
public void unRegisterReceiver(){
Log.d("ali", "unRegisterReceiver");
mContext.unregisterReceiver(this);
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.d("ali", "in PROVIDERS_CHANGED");
mCallback.onGpsStatusChange();
}
}
public interface GpsStatusChangeListener{
void onGpsStatusChange();
}
}
4. Create a class GPSLocation
public class GPSLocation implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
GPSStatusReceiver.GpsStatusChangeListener {
public static final int REQUEST_CHECK_SETTINGS = 100;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 200;
private static final int PERMISSION_GRANTED = 0;
private static final int PERMISSION_DENIED = 1;
private static final int PERMISSION_BLOCKED = 2;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private LocationCallback mCallback;
private Activity mActivity;
private Context mContext;
private LocationRequest mLocationRequest;
private GPSStatusReceiver mGPSStatusReceiver;
private long intervalMillis = 10000;
private long fastestIntervalMillis = 5000;
private int accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;
private boolean isInitialized = false;
private boolean isLocationEnabled = false;
private boolean isPermissionLocked = false;
public GPSLocation(Activity activity, LocationCallback callback) {
mActivity = activity;
mContext = activity.getApplicationContext();
mCallback = callback;
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGPSStatusReceiver = new GPSStatusReceiver(mContext, this);
}
public void init(){
isInitialized = true;
if(mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
requestPermission();
} else {
connect();
}
}
}
public void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(intervalMillis);
mLocationRequest.setFastestInterval(fastestIntervalMillis);
mLocationRequest.setPriority(accuracy);
}
public LocationRequest getLocationRequest() {
return mLocationRequest;
}
public void connect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.connect();
}
}
public void disconnect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.disconnect();
}
}
private void getLastKnownLocation(){
if(!mGoogleApiClient.isConnected()){
Log.d("ali", "getLastKnownLocation restart ");
mGoogleApiClient.connect();
}
else {
if (checkLocationPermission(mContext) && isLocationEnabled) {
Log.d("ali", "getLastKnownLocation read ");
if(mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mCallback.onLastKnowLocationFetch(mCurrentLocation);
}
startLocationUpdates();
}else{
Log.d("ali", "getLastKnownLocation get permission ");
requestPermission();
}
}
Log.d("ali", "mCurrentLocation " + mCurrentLocation);
}
public void startLocationUpdates() {
if(checkLocationPermission(mContext)
&& mGoogleApiClient != null
&& mGoogleApiClient.isConnected()
&& isLocationEnabled) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
public void stopLocationUpdates() {
if(mGoogleApiClient != null
&& mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("ali", "onConnected");
requestPermission();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("ali", "onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d("ali", "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.d("ali", "onLocationChanged : " + location);
mCallback.onLocationUpdate(location);
}
#Override
public void onGpsStatusChange() {
Log.d("ali", "onGpsStatusChange");
if(isInitialized && !isPermissionLocked) {
if (!isLocationEnabled(mContext)) {
isLocationEnabled = false;
isPermissionLocked = true;
stopLocationUpdates();
requestPermission();
}
}
}
private void requestPermission(){
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
String[] appPerm = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(mActivity, appPerm, LOCATION_PERMISSION_REQUEST_CODE);
}else{
getLocationSetting();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
if (resultCode == Activity.RESULT_OK) {
getLastKnownLocation();
}else{
Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
}
}
}
private void getLocationSetting(){
LocationSettingsRequest.Builder builder =
new LocationSettingsRequest
.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d("ali", "SUCCESS");
isLocationEnabled = true;
isPermissionLocked = false;
getLastKnownLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.d("ali", "RESOLUTION_REQUIRED");
try {
status.startResolutionForResult(
mActivity,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
mCallback.onLocationSettingsError();
}finally {
isPermissionLocked = false;
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d("ali", "SETTINGS_CHANGE_UNAVAILABLE");
Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
isPermissionLocked = false;
break;
}
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permState;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(
mActivity,
Manifest.permission.ACCESS_FINE_LOCATION)){
permState = PERMISSION_BLOCKED;
}else{permState = PERMISSION_DENIED;}
}else {permState = PERMISSION_GRANTED;}
}
else{permState = PERMISSION_DENIED;}
switch (permState){
case PERMISSION_BLOCKED:
Toast.makeText(mContext,"Please give gps location permission to use the app.",Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity(mContext);
mCallback.onLocationPermissionDenied();
break;
case PERMISSION_DENIED:
Toast.makeText(mContext,"Permission Denied, app cannot access the gps location.", Toast.LENGTH_LONG).show();
break;
case PERMISSION_GRANTED:
getLocationSetting();
break;
}
break;
}
}
public static boolean isLocationEnabled(Context context){
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = false;
boolean networkEnabled = false;
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
return gpsEnabled && networkEnabled;
}
public static void startInstalledAppDetailsActivity(final Context context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
public static boolean checkLocationPermission(Context context) {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
public interface LocationCallback {
void onLastKnowLocationFetch(Location location);
void onLocationUpdate(Location location);
void onLocationPermissionDenied();
void onLocationSettingsError();
}
public void close() {
mGPSStatusReceiver.unRegisterReceiver();
}
}
5. In the activity use the below code
public class MainActivity extends AppCompatActivity implements GPSLocation.LocationCallback {
private GPSLocation mGPSLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGPSLocation = new GPSLocation(this, this);
mGPSLocation.init();
}
#Override
public void onLastKnowLocationFetch(Location location) {
if(location != null) {
Log.d("ali ", "onLastKnowLocationFetch " + location);
}
}
#Override
public void onLocationUpdate(Location location) {
if(location != null) {
Log.d("ali ", "onLocationUpdate " + location);
}
}
#Override
public void onLocationPermissionDenied() {
}
#Override
public void onLocationSettingsError() {
}
#Override
protected void onStart() {
mGPSLocation.connect();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mGPSLocation.startLocationUpdates();
}
#Override
protected void onPause() {
super.onPause();
mGPSLocation.stopLocationUpdates();
}
#Override
protected void onStop() {
mGPSLocation.disconnect();
super.onStop();
}
#Override
protected void onDestroy() {
mGPSLocation.close();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE) {
mGPSLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
mGPSLocation.onActivityResult(requestCode, resultCode, data);
}
}
}
The following code checks, if location is enabled or not. If not it shows alert dialog to enable location service.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Startup.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
add below code in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add this override method for me its worked fine--
#Override
public void onLocationChanged(Location location) {
getLocation("onLocationChanged");
}