Google Location Services API, not accurate location - android

I am using the following code to get accurate location of user, however I have to say that location is not accurate. It varies within 30meters which is not acceptable if you wanna get exact location for crucial purposes. I use the code below (followed a tutorial) to get the accurate location however it's not precise. Any hints on how to get more preferably 100% accurate position.
Activity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Nieuwe Locatie Toevoegen");
setSupportActionBar(toolbar);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Enable Gps Location plaeast");
dialog.setPositiveButton("Ja ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Nee liever niet", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
if (checkGooglePlayServices()) {
buildGoogleApiClient();
//prepare connection request
createLocationRequest();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private boolean checkGooglePlayServices() {
int checkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
/*
* google play services is missing or update is required
* return code could be
* SUCCESS,
* SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED,
* SERVICE_DISABLED, SERVICE_INVALID.
*/
GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,
this, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_RECOVER_PLAY_SERVICES) {
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Google Play Services must be installed.",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//
// Toast.makeText(this, "Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
String city = addresses.get(0).getLocality();
String address = addresses.get(0).getAddressLine(0);
String postalCode = addresses.get(0).getPostalCode();
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("You locatie momenteel is : "+ " " + address + " " + city + " " + postalCode);
dialog.setPositiveButton("Ja dit klopt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
//Toast.makeText(this, "Stad:" + city + " Straat: "+ address + " Postcode :" + postalCode, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
// Second Part
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(20000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Toast.makeText(this, "Update -> Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
protected void stopLocationUpdates() {
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
}
Thanks in advance,

Related

Fused Location Provider issues

I am using Fused Location Api for getting the latitude and longitude.It's mentioned in the documents that it uses GPS, Wifi and network(Cell) to return the most accurate location of the user. I've a couple of questions here:
1)I've noticed that if I turn off the wifi, it still gives the result but it gives null when GPS is turned off, why is that? Isn't it suppose to use the Wifi to give the location detail even if gps is off or not available? P.S. I've used ACCESS_FINE_LOCATION for permission.
2)How can I know/test whether the location detail is returned using Wifi or GPS or network (Cell tower)?
3)Will it work using network (cell tower) when both GPS and wifi are off?
Fused Location Provider code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
if (checkPlayServices()) {
Log.i("playservice", checkPlayServices()+"");
// Building the GoogleApi client
buildGoogleApiClient();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected!");
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i(TAG, " Location: " + mLastLocation);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(final LocationResult locationResult) {
Log.i("onLocationResult",locationResult + "");
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lblLocation.setText(locationResult.getLocations() + "");
}
});
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable = " + locationAvailability.isLocationAvailable());
}
}, null);
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
Log.i(TAG, "mGoogleApiClient.connect()");
}
}
When I've GPS on, the output I get is:
I/onLocationResult(7481): LocationResult[locations: [Location[fused 27.673576,85.314083 acc=16 et=+1d1h59m30s347ms alt=1289.0999755859375 vel=0.93 bear=166.0]]]

How to ask if location is enabled before map initializes?

How to ask if location is enabled before map initializes ?
If I try to ask for permission on MapsActivity all it does is quit the application because it is not enabled.
I have tried adding it to the activity that directs the users to the Map. But it still just closes the activity unless the location is enabled.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
setUpMap();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onResume() {
super.onResume();
setUpMap();
}
private void setUpMap() {
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
Marker mClosestMarker;
float mindist;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
void createMarkersFromJson(String json) throws JSONException {
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;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
double lat = jsonObj.getJSONArray("latlng").getDouble(0);
double lon = jsonObj.getJSONArray("latlng").getDouble(1);
final String address = jsonObj.getString("address");
Marker currentMarker = mMap.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population"))).draggable(true)
.position(new LatLng(jsonObj.getJSONArray("latlng").getDouble(0), jsonObj.getJSONArray("latlng").getDouble(1)))
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Call Local Distributor " + marker.getTitle())
.setMessage("Would you like to dial now ? ")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + marker.getSnippet()));
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.create()
.show();
return true;
}
});
float[] distance = new float[1];
Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), lat, lon, distance);
if (i == 0) {
mindist = distance[0];
} else if (mindist > distance[0]) {
mindist = distance[0];
mClosestMarker = currentMarker;
Toast.makeText(getApplicationContext(),
mClosestMarker.getTitle(), Toast.LENGTH_LONG)
.show();
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(100);
mLocationRequest.setFastestInterval(100);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_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(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
}
}
I tired using this snippet in OnCreate, but still if location is disabled the application fails to start.
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
below is my code snippet that i use for my application it works fine check it it will work for you as well
int off = 0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if (off == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("GPS is not enbled.");
builder.setMessage("To Get Your Current Location You have To Enable Gps \n Are Sure Want to go to seeting to Enable GPS?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
// Toast.makeText(MapsActivity.this, c_lat +","+c_long, Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();

How to update longitude and latitude in every 10 seconds in mysql database?

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!

How to implement a service that will wait for GPS signal

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.

How Test Location Change in Genny motion

How Test Location change from One position To another In genny motion
Here I posted My code Where On onLocationChanged never called
public class RouteMapActivity extends AppCompatActivity implements
LocationListener, OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final int LOCATION_SETTINGS_REQUEST_CODE = 1;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
private static final LatLng latlngHiLiteMall = new LatLng(11.248823, 75.833760);
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
private static int UPDATE_INTERVAL = 10000;
private static int FATEST_INTERVAL = 5000; /
private static int DISPLACEMENT = 10;
boolean isGPSTrackingEnabled = false;
LatLng latLngMyLocation = null;
AlertDialog alertDlg;
GoogleApiClient googleApiClient;
LocationSettingsRequest.Builder builder;
double myLocLat, myLocLong;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
ConnectionInfo connectionInfo;
private Location mLastLocation;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
connectionInfo = new ConnectionInfo(this);
Log.e("Rout Map.....","on Create....!");
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
setUpMapIfNeeded();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled)
showAlertDialog();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
startLocationUpdates();
Log.d("TAG", "Periodic location updates started!");
} else {
mRequestingLocationUpdates = false;
stopLocationUpdates();
Log.d("TAG", "Periodic location updates stopped!");
}
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mMap == null) {
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (!isGPSEnabled) {
Toast.makeText(RouteMapActivity.this, "GPS is disabled!", Toast.LENGTH_SHORT).show();
}
return false;
}
});
// Add a marker in Sydney and move the camera
mMap.addMarker(new MarkerOptions().position(latlngHiLiteMall).title("HiLite Mall"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlngHiLiteMall, 12));
//getMyCurrentLocation();
getMyLocation();
}
private void getMyLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
if (mLastLocation != null) {
Log.d("NOT NULL", ">>>>>>>>>>>");
if (alertDlg != null && alertDlg.isShowing())
alertDlg.dismiss();
myLocLat = mLastLocation.getLatitude();
myLocLong = mLastLocation.getLongitude();
if (connectionInfo.isConnectingToInternet()) {
latLngMyLocation = new LatLng(myLocLat, myLocLong);
mMap.addMarker(new MarkerOptions().position(latLngMyLocation).title("My Loc"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngMyLocation, 12));
new MapTask().execute();
} else {
Toast.makeText(this, "Enable Internet", Toast.LENGTH_SHORT).show();
}
Toast.makeText(RouteMapActivity.this, "G--" + myLocLat, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RouteMapActivity.this, "Couldn't get the location. Make sure location is enabled on the device", Toast.LENGTH_SHORT).show();
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
Log.d("last known location", "" + provider + " " + l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy())
{
Log.d("last known location", "" + provider + " " + l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Use Location?");
alertDialog.setMessage("Helps for find the route to HiLite Mall.");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDlg = alertDialog.create();
alertDlg.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOCATION_SETTINGS_REQUEST_CODE) {
Log.d("TAG", "Activity Result");
getMyLocation();
}
}
#Override
public void onConnected(Bundle connectionHint) {
getMyLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("API CLIENT", "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
Log.i("API CLIENT", "Connection suspended");
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.e("Location Changed.....","Location changed....!");
mLastLocation = location;
// Displaying the new location on UI
getMyLocation();
}
private class MapTask extends AsyncTask<Void, Void, PolylineOptions> {
#Override
protected PolylineOptions doInBackground(Void... params) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(latLngMyLocation, latlngHiLiteMall, GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
return rectLine;
}
#Override
protected void onPostExecute(PolylineOptions rectLine) {
mMap.addPolyline(rectLine);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use the Emulator Control of DDMS to change the location.

Categories

Resources