I am new to Android Studio and firebase. Making an android app for my final year project. I want to save the location of the user under the username under the BusinessOwner field. I want to save the location of the user when signing in. Your help will be really appreciated
I have my firebase database like this now
I want it to be like this
BusinessOwnerRegister.java
package com.example.android.onroadsupport;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class BusinessOwnerRegister extends AppCompatActivity {
//Variables
TextInputLayout regName, regUsername, regEmail, regPhoneNo, regPassword,regFullAddress,regLandmark,regPinCode,regVoterID,regServiceType;
Button regBtn;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_owner_register);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Hooks to all xml elements in activity_user_register.xml
regName = findViewById(R.id.reg_name);
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNumber);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regFullAddress = findViewById(R.id.reg_address);
regLandmark = findViewById(R.id.reg_landmark);
regPinCode = findViewById(R.id.reg_pinCode);
regVoterID = findViewById(R.id.reg_voterID);
regServiceType = findViewById(R.id.reg_serviceType);
}
private Boolean validateName() {
String val = regName.getEditText().getText().toString();
if (val.isEmpty()) {
regName.setError("Field cannot be empty");
return false;
} else {
regName.setError(null);
regName.setErrorEnabled(false);
return true;
}
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White Spaces are not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
regEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
regPhoneNo.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
private Boolean validateFullAddress() {
String val = regFullAddress.getEditText().getText().toString();
if (val.isEmpty()) {
regFullAddress.setError("Field cannot be empty");
return false;
} else {
regFullAddress.setError(null);
regFullAddress.setErrorEnabled(false);
return true;
}
}
private Boolean validateLandmark() {
String val = regLandmark.getEditText().getText().toString();
if (val.isEmpty()) {
regLandmark.setError("Field cannot be empty");
return false;
} else {
regLandmark.setError(null);
regLandmark.setErrorEnabled(false);
return true;
}
}
private Boolean validatePinCode() {
String val = regPinCode.getEditText().getText().toString();
if (val.isEmpty()) {
regPinCode.setError("Field cannot be empty");
return false;
} else {
regPinCode.setError(null);
regPinCode.setErrorEnabled(false);
return true;
}
}
private Boolean validateVoterID() {
String val = regVoterID.getEditText().getText().toString();
if (val.isEmpty()) {
regVoterID.setError("Field cannot be empty");
return false;
} else {
regVoterID.setError(null);
regVoterID.setErrorEnabled(false);
return true;
}
}
private Boolean validateServiceType() {
String val = regServiceType.getEditText().getText().toString();
if (val.isEmpty()) {
regServiceType.setError("Field cannot be empty");
return false;
} else {
regServiceType.setError(null);
regServiceType.setErrorEnabled(false);
return true;
}
}
//This function will execute when user click on Sign up Button
public void registerBusinessOwner(View view) {
//Save data in firebase on button click
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("BusinessOwners");
if (!validateName() | !validateUsername() | !validateEmail() | !validatePhoneNo() | !validatePassword() |
!validateFullAddress() | !validateLandmark() | !validatePinCode() | !validateVoterID() | !validateServiceType()) {
return;
}
//Get all the values in Strings
String name = regName.getEditText().getText().toString();
String username = regUsername.getEditText().getText().toString();
String email = regEmail.getEditText().getText().toString();
String phoneNo = regPhoneNo.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
String fullAddress = regFullAddress.getEditText().getText().toString();
String landmark = regLandmark.getEditText().getText().toString();
String pinCode = regPinCode.getEditText().getText().toString();
String voterID = regVoterID.getEditText().getText().toString();
String serviceType = regServiceType.getEditText().getText().toString();
//Storing data in Firebase
MechanicHelperClass mechanicHelperClass = new MechanicHelperClass(name, username, email, phoneNo, password, fullAddress, landmark, pinCode, voterID, serviceType);
//Adding multiple users
//Adding username as unique ID
reference.child(username).setValue(mechanicHelperClass);
Toast.makeText(this, "Your Account has been Created Successfully!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Add Your Location", Toast.LENGTH_SHORT).show();
//Calling Login screen after Sign up completed
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
finish();
}
}
MapsActivity.java
package com.example.android.onroadsupport;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.android.onroadsupport.databinding.ActivityMapsBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
Button callLogin;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2000;
private long FASTEST_INTERVAL = 5000;
private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Call login from map
callLogin = findViewById(R.id.callLoginFromMap);
callLogin.setOnClickListener(v -> {
Intent intent = new Intent(MapsActivity.this, BusinessOwnerLogin.class);
startActivity(intent);
});
if (requestSinglePermission()) {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
}
private boolean checkLocation() {
if (!isLocationEnabled()){
showAlert();
}
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your location setting is set to off \n Please enable location to" + "use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean requestSinglePermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
isPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
//Check for permanent denial of permission
if (response.isPermanentlyDenied()) {
isPermission = false;
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
return isPermission;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (latLng!=null){
mMap.addMarker(new MarkerOptions().position(latLng).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14f));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null){
startLocationUpdates();
}
else{
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
private void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL).setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient
,mLocationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(#NonNull Location location) {
String msg = "Updated Location : " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
LocationHelper locationHelper = new LocationHelper(
location.getLongitude(),
location.getLatitude()
);
FirebaseDatabase.getInstance().getReference("BusinessOwners").child("Current Location")
.setValue(locationHelper).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MapsActivity.this, "Location Saved", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MapsActivity.this, "Location Not Saved", Toast.LENGTH_SHORT).show();
}
}
});
latLng = new LatLng(location.getLatitude(),location.getLongitude());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null){
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
}
Related
I am Trying to Build an app where user can show their location and send an SMS to nearby hospital.
I am new to android studio and everything about it, but I quite made a progress with it.
I have 2 XML files, but I'll provide the JAVA CLASSES first
MapActivity.java
package maptesting.app;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import maptesting.app.databinding.ActivityMapBinding;
public class MapActivity<mapView> extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private ActivityMapBinding binding;
private View mapView;
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private LocationManager locationManager;
private Marker currentLocationmMarker;
public static final int REQUEST_LOCATION_CODE = 99;
int PROXIMITY_RADIUS = 15000;
double latitude, longitude;
private int LOCATION_MIN_DISTANCE = 20;
private int LOCATION_MIN_TIME = 4000;
private boolean requestingLocationUpdates;
//NEW
private int FINE_LOCATION_REQUEST_CODE = 10001;
private float Geofence_Radius = 4000;
private Object CircleOptions;
//NEW SMS
private LocationListener locationListener;
private final long mTime = 1000;
private final long mDist = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (!isConnectedToNetwork()) {
Toast.makeText(this, "Turn on mobile data or Wifi", Toast.LENGTH_LONG).show();
finish();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
} else {
Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
// View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
//locationButton.callOnClick();
}
//NEW INPUT (SMS)
LatLng msgloc = new LatLng(lastlocation.getLatitude(), lastlocation.getLongitude());
locationListener = new LocationListener()
{
#Override
public void onLocationChanged(#NonNull Location location)
{
try
{
String phoneNum = "09553625915";
String loc = String.valueOf(msgloc);
String message = "Location = " + msgloc;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, message, null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onProviderEnabled(#NonNull String provider)
{
}
public void onProviderDisabled(#NonNull String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
}
catch (SecurityException e)
{
e.printStackTrace();
}
//END NEW INPUT (SMS)
}
private void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
#Override
public void onLocationChanged(#NonNull Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if (currentLocationmMarker != null)
{
currentLocationmMarker.remove();
}
Log.d("lat = ", "" + latitude);
Log.d("lng = ", "" + longitude);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
AddCircle(latLng, Geofence_Radius);
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//currentLocationmMarker = mMap.addMarker(markerOptions);
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;
}
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//mMap.animateCamera(CameraUpdateFactory.zoomBy(2));
//todo delete following lines
Object[] dataTransfer = new Object[2];
getNearbyPlacesData getNearbyPlacesData = new getNearbyPlacesData();
String url = getUrl(latitude, longitude, "hospital");
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
//todo end
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location=" + latitude + "," + longitude);
googlePlaceUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlaceUrl.append("&type=" + nearbyPlace);
googlePlaceUrl.append("&sensor=true");
//Todo: add your google api key here
googlePlaceUrl.append("&key=" + "YOUR_API_KEY");
Log.d("MapsActivity", "url = " + googlePlaceUrl.toString());
return googlePlaceUrl.toString();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(5);
locationRequest.setFastestInterval(500);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// ORG
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
private boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private boolean isConnectedToNetwork() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
}
// Add Circle
private void AddCircle(LatLng latLng, float radius)
{
mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(Geofence_Radius)
.strokeColor(Color.argb(50, 0, 0, 0))
.fillColor(Color.argb(13,0,0,0))
.strokeWidth(4));
}
What I want to see if its possible to send the user's current location to another phone after I hit the button that will also show their current location in the map.
I am willing to provide the source code if you kind sirs and ma'ams want to check my code.
Thank you
Initially I displayed the current latitude and longitude in the application using the following code:
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
#Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
if (!isContinue) {
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
#SuppressLint("MissingPermission")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
When I did this the code was working well. Then I tried to update the code as I needed to display the State of the current location as well "i.e. Display the state in where the users Phone is currently located(e.g. South Carolina, Massachusetts, California, etc.).
This was the updated code:
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
#Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName());
}
} catch (IOException e){
}
if (!isContinue) {
txtLocation.setText(stringBuilder.toString());
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
#SuppressLint("MissingPermission")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
This code now doesn't even display the current latitude and longitude. Can someone help me with this. I'm looking to display the State as well as the Lat and Long of the current location.
The lines of Code where the changes have been implemented and that seems the most relevant to my issue are marked with a long line of asterisk at the Start and End of the code which looks like this:
*******************************************************
All we need to do is add this permission in the manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And create a LocationManager instance like this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Check if GPS is enabled or not.
And then implement LocationListener and get coordinates:
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Here is the sample code to do so
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
see this flow:
How do I get the current GPS location programmatically in Android?
Actually this code will not work now.
Google has deprecated the above code and now you need to use below code.
I used Retrofit
Retrofit Client
public static final String GOOGLE_ETA = "https://maps.googleapis.com/maps/";
public static Retrofit getEtaClient() {
if (retrofitEtaGoogle == null) {
retrofitEtaGoogle = new Retrofit.Builder()
.baseUrl(GOOGLE_ETA)
.client(provideOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitEtaGoogle;
}
Api interface class
#GET("api/geocode/json?key="+ Consts.GOOGLE_API_KEY)
Call<GoogleGeoCodeApiResponseModel> getPlaceFromLatLng(#Query("latlng") String latLng);
In updateLocationUI() method
String latLng = location.getLatitude() + "," + location.getLongitude();
ApiInterface apiInterface = RetrofitClient.getEtaClient().create(ApiInterface.class);
Call<GoogleGeoCodeApiResponseModel> call = apiInterface.getPlaceFromLatLng(latLng);
call.enqueue(new Callback<GoogleGeoCodeApiResponseModel>() {
#Override
public void onResponse(Call<GoogleGeoCodeApiResponseModel> call, Response<GoogleGeoCodeApiResponseModel> response) {
if (response.body().getStatus() != null && response.body().getStatus().equals("OK")) {
addressObj = new GoogleAddressLocalModel();
addressObj.setName(response.body().getResults().get(0).getFormattedAddress());
addressObj.setLat(response.body().getResults().get(0).getGeometry().getLocation().getLat());
addressObj.setLng(response.body().getResults().get(0).getGeometry().getLocation().getLng());
for (GoogleGeoCodeApiResponseModel.AddressComponent obj : response.body().getResults().get(0).getAddressComponents()) {
for (String type : obj.getTypes()) {
if (type.contains("postal_code")) {
addressObj.setPostalCode(obj.getLongName());
} else if (type.contains("country")) {
addressObj.setCountryId(obj.getShortName());
addressObj.setCountryName(obj.getLongName());
} else if (type.contains("administrative_area_level_2")) {
addressObj.setCityName(obj.getLongName());
}
}
}
} else if (response.body().getStatus() != null) {
Log.e("ErrroGettingAddress", response.body().getStatus());
}
}
#Override
public void onFailure(Call<GoogleGeoCodeApiResponseModel> call, Throwable t) {
Log.e("ErrroGettingAddress", t.getLocalizedMessage());
}
});
}
I have tried to figure this out for the past 48 hours, but I must be an idiot. I followed the Google documentation to try and make this weather app location aware. The problem is I don't how to make onLocationChanged() run or even know when it is supposed to run. If it doesn't run I send a request to grab data from latitude 0 and longitude 0. I have enabled all the correct permissions. Please help me...
package com.brennanglynn.brennanweather.ui;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.brennanglynn.brennanweather.R;
import com.brennanglynn.brennanweather.weather.Current;
import com.brennanglynn.brennanweather.weather.Day;
import com.brennanglynn.brennanweather.weather.Forecast;
import com.brennanglynn.brennanweather.weather.Hour;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static final String TAG = MainActivity.class.getSimpleName();
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
public static final String BG_GRADIENT = "BG_GRADIENT";
private Forecast mForecast;
private ColorWheel mColorWheel;
private int[] mBackground;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
private double mLatitude;
private double mLongitude;// = -116.2296;
#BindView(R.id.layoutBackground)
RelativeLayout mLayoutBackground;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
mColorWheel = new ColorWheel();
mProgressBar.setVisibility(View.INVISIBLE);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateDisplay();
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void setBackgroundGradient() {
mBackground = mColorWheel.getColors();
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{mBackground[0], mBackground[1]});
gd.setCornerRadius(0f);
mLayoutBackground.setBackground(gd);
}
private void getForecast(double latitude, double longitude) {
String apiKey = "50e826df5889d0d215cdcbae50d182e3";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
alertUserAboutError();
}
Log.i(TAG, forecastUrl);
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrentForecast(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Day day = new Day();
day.setTime(jsonHour.getLong("time"));
day.setSummary(jsonHour.getString("summary"));
day.setTemperatureMax(jsonHour.getInt("temperatureMax"));
day.setTimezone(timezone);
day.setIcon(jsonHour.getString("icon"));
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setTime(jsonHour.getLong("time"));
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getInt("temperature"));
hour.setTimezone(timezone);
hour.setIcon(jsonHour.getString("icon"));
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current(
currently.getString("icon"),
currently.getLong("time"),
currently.getDouble("temperature"),
currently.getDouble("humidity"),
currently.getDouble("precipProbability"),
currently.getString("summary"),
forecast.getString("timezone")
);
Log.i(TAG, current.toString());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.refreshImageView)
public void refreshPage(View view) {
mRequestingLocationUpdates = true;
getForecast(mLatitude, mLongitude);
setBackgroundGradient();
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
#OnClick(R.id.hourButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
startLocationUpdates();
}
}
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
stopLocationUpdates();
}
}
protected void startLocationUpdates() {
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void updateDisplay() {
Current current = mForecast.getCurrentForecast();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("The time is " + current.getFormattedTime());
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ResourcesCompat.getDrawable(getResources(), current.getIconId(), null);
mIconImageView.setImageDrawable(drawable);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
//
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
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;
}
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "location changed");
mCurrentLocation = location;
mLatitude = mCurrentLocation.getLatitude();
mLongitude = mCurrentLocation.getLongitude();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
getForecast(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
updateDisplay();
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
}
hi your api is working fine, i have checked. You have issue with your current latitude and longitude. So, i have one solution for you.
Please check how i'm using in my app and its working perfect.I'm using fused api for update location please follow few steps.
Step 1. Make this class
GoogleLocationService.java
public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;
public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
this.locationUpdateListener = locationUpdateListener;
this.activity = activity;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
//Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(callbacks)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
}
locationUpdateListener.cannotReceiveLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
}
}
}
}
private static boolean locationEnabled(Context context) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
return gps_enabled;
}
private boolean servicesConnected(Context context) {
return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
public void startUpdates() {
/*
* Connect the client. Don't re-start any requests here; instead, wait
* for onResume()
*/
if (servicesConnected(activity)) {
if (locationEnabled(activity)) {
locationUpdateListener.canReceiveLocationUpdates();
startLocationUpdates();
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
}
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
}
}
//stop location updates
public void stopUpdates() {
stopLocationUpdates();
}
//start location updates
private void startLocationUpdates() {
if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
}
}
public void stopLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
}
}
public void startGoogleApi() {
mGoogleApiClient.connect();
}
public void closeGoogleApi() {
mGoogleApiClient.disconnect();
}
}
Step2. Make this interface
LocationUpdateListener.java
public interface LocationUpdateListener {
/**
* Called immediately the service starts if the service can obtain location
*/
void canReceiveLocationUpdates();
/**
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
*/
void cannotReceiveLocationUpdates();
/**
* Called whenever the location has changed (at least non-trivially)
* #param location
*/
void updateLocation(Location location);
/**
* Called when GoogleLocationServices detects that the device has moved to a new location.
* #param localityName The name of the locality (somewhere below street but above area).
*/
void updateLocationName(String localityName, Location location);
}
Step 3. Call this in your class oncreate or where you want to get location
private GoogleLocationService googleLocationService;
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
#Override
public void canReceiveLocationUpdates() {
}
#Override
public void cannotReceiveLocationUpdates() {
}
//update location to our servers for tracking purpose
#Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());
}
}
#Override
public void updateLocationName(String localityName, Location location) {
googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
and call this onDestroy
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
Hope this will help you to solve your problem.
Hi am running with an issue. I have a gps checking function on my splash screen where after checking my gps connectivity if its state is null it shows an alert.I want to destroy and restart my application after the button click of alert box. Kindly help. here is my code
Geolocationfinder class
package com.driverapp.inis.zuber;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class GeoLocationFinder {
private static final String TAG = "GeoLocationFinder";
Timer locationTimer;
LocationManager locationManager;
private static final int min_update_time = 3000; // in msec
private static final int min_distance_for_update = 10; // in meters
LocationResult locationResult;
boolean gps_enabled = Boolean.FALSE;
boolean network_enabled = Boolean.FALSE;
private AlertDialogManager alert;
Context ctx;
public boolean getLocation(Context ctx, LocationResult result) {
this.ctx = ctx;
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) ctx
.getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
/* alert = new AlertDialogManager();
alert.showAlertDialog(ctx, "Error", "GPS enabled exception:", false);*/
Log.d(TAG, "GPS enabled exception: " + e.getMessage());
}
try {
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
Log.d(TAG, "Network enabled exception: " + e.getMessage());
}
if (!gps_enabled && !network_enabled) {
alert = new AlertDialogManager();
alert.showAlertDialog(ctx, "Error", "Please Check Your GPS Connection and Try Again", false);
return Boolean.FALSE;
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, min_update_time,
min_distance_for_update, locationListenerGps);
}
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, min_update_time,
min_distance_for_update, locationListenerNetwork);
}
locationTimer = new Timer();
locationTimer.schedule(new GetLastLocation(), 2000);
return Boolean.TRUE;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "GPS provider disabled" + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "GPS provider enabled" + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "GPS status changed");
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Network provider disabled. " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Network provider enabled. " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "Network status changed.");
}
};
private class GetLastLocation extends TimerTask {
#Override
public void run() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled) {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled) {
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime()) {
locationResult.gotLocation(gps_loc);
} else {
locationResult.gotLocation(net_loc);
}
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
else {
locationResult.gotLocation(null);
}
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Splashscreen class
package com.driverapp.inis.zuber;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import Connectivity_manager.Internet_CheckingActivity;
public class Splashscreen extends Activity {
private static final String TAG = "SplashScreenActivity";
private Location newLocation = null;
private AlertDialogManager alert;
private Internet_CheckingActivity chckInternt;
private GeoLocationFinder geoLocationFinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
alert = new AlertDialogManager();
chckInternt = new Internet_CheckingActivity(this);
}
#Override
protected void onResume() {
super.onResume();
// setupLocation();
if (chckInternt.isNetworkAvailable() == true) {
setupLocation();
}
else
{
alert.showAlertDialog(Splashscreen.this, "Error", "Please Check Your Internet Connection", false);
}
}
/** Method for checking the current lat log values. */
private void setupLocation() {
GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ newLocation.getLongitude() + " Latitude = "
+ newLocation.getLatitude());
Intent i = new Intent(Splashscreen.this, LoginActivity.class);
startActivity(i);
finish();
} else{
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
alert.showAlertDialog(Splashscreen.this, "Check Your GPS", "Restart your Application", false);
}
});
}
}
};
geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this,locationResult);
}
}
AlertDialogManager class
package com.driverapp.inis.zuber;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextThemeWrapper;
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public int setOk = 0;
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
AlertDialog.Builder alertDialog= new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom));
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.setCancelable(Boolean.FALSE);
alertDialog.show();
}
/*Aler used for the delete in sheet details*/
public void showAlertDialogDelete(final Context context, String title, String message,
Boolean status) {
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
AlertDialog.Builder alertDialog= new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom));
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(context, Splashscreen.class);
context.startActivity(in);
}
});
// Showing Alert Message
alertDialog.setCancelable(Boolean.FALSE);
alertDialog.show();
}
}
Add the following code in OnClick() method of the Positive buton:
Intent intent = new Intent(context, Splashscreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
It will clear the activity stack of your application and launch Splashscreen activity.
I'm trying to acquire GPS coordinates on my android application.
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
LocationManager locationManager =
(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent i = new Intent(context, IntentListener.class);
i.setAction(Actions.ACTION_UPDATE_LOCATION);
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String provider = locationManager.getBestProvider(criteria, true);
if (provider == null) return;
locationManager.requestLocationUpdates(provider, 90 * 1000, 30, pi);
and here's receiving code.
Intent service = new Intent(context, WorkerService.class);
service.setAction(Actions.ACTION_UPDATE_LOCATION);
Location location = (Location) intent.getExtras().get(
LocationManager.KEY_LOCATION_CHANGED);
if (location == null) { // <-- Always true
return;
}
service.putExtra("lat", location.getLatitude());
service.putExtra("lon", location.getLongitude());
context.startService(service);
As you can see, I'm unable to obtain Location instance by calling intent.getExtras()... etc. Returned value is always null. I'm testing on my emulator running android 4.1.2 and telnet client, using geo fix longitude latitude. Anyone knows what's wrong? Thanks.
P.S. Manifest contains all required permissions and GPS is enabled in the emulator.
P.P.S. This application is a corporate app, that runs as a service, without UI and should collect GPS coordinates.
You casually mentioned that you're testing on an emulator. The emulator doesn't receive mock locations by itself; you have to specifically send them through the DDMS interface.
Additionally, due to a bug in the emulator, the time offset in incoming locations is set to midnight, so your location criteria will likely not match it.
I strongly suggest you test with a physical device to confirm that the problem is still occurring.
Use the new Location API.
You'd have to include Google Play services into your project.
Add this in onCreate:
mIntentService = new Intent(this,LocationService.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
locationclient = new LocationClient(this,this,this);
locationclient.connect();
}
And you'd have to override these methods:
#Override
protected void onDestroy() {
super.onDestroy();
if(locationclient!=null)
locationclient.disconnect();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "onConnected");
//to get last location
Location loc =locationclient.getLastLocation();
//to get updates via service
locationrequest = LocationRequest.create();
locationrequest.setInterval(100);
locationclient.requestLocationUpdates(locationrequest, mPendingIntent);
}
#Override
public void onDisconnected() {
Log.i(TAG, "onDisconnected");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
if(location!=null){
Log.i(TAG, "Location Request :" + location.getLatitude() + "," + location.getLongitude());
}
}
Here's the service where I'm creating a notification for every new location, you can remove that and update location there.
public class LocationService extends IntentService {
private String TAG = this.getClass().getSimpleName();
public LocationService() {
super("Fused Location");
}
public LocationService(String name) {
super("Fused Location");
}
#Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if(location !=null){
Log.i(TAG, "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Builder noti = new NotificationCompat.Builder(this);
noti.setContentTitle("Fused Location");
noti.setContentText(location.getLatitude() + "," + location.getLongitude());
noti.setSmallIcon(R.drawable.ic_launcher);
notificationManager.notify(1234, noti.build());
}
}
}
Follow the tutorial to get the location in Android app
You should take your location by implementing LocationListener
#Override
public void onLocationChanged(Location loc) {
}
Take a look at this implementation, works really nice and i have tested it on several devices.
package ro.gebs.captoom.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.bugsense.trace.BugSenseHandler;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import ro.gebs.captoom.R;
import ro.gebs.captoom.database.ReceiptDataSource;
import ro.gebs.captoom.utils.Constants;
import ro.gebs.captoom.utils.Utils;
public class LocationActivity extends FragmentActivity {
private GoogleMap map;
private long rec_id;
private String address;
private Marker selectedLoc;
private boolean isSessionClosed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
BugSenseHandler.initAndStartSession(this, Constants.BugSenseKEY);
setContentView(R.layout.preview_location);
RelativeLayout cancel_btn = (RelativeLayout) findViewById(R.id.cancel_btn);
LinearLayout save_location_btn = (LinearLayout) findViewById(R.id.delete_btn);
save_location_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (address != null) {
ReceiptDataSource r = new ReceiptDataSource();
r.updateReceiptLocation(rec_id, address);
Intent returnIntent = new Intent(getBaseContext(), EditReceiptActivity.class);
returnIntent.putExtra("result", address);
setResult(RESULT_OK, returnIntent);
finish();
} else {
Utils.showToast(getApplicationContext(), getString(R.string.c_unknownLocation), Toast.LENGTH_SHORT);
}
}
});
cancel_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (isGoogleMapsInstalled()) {
if (map != null) {
retrieveLocation();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Install Google Maps");
builder.setCancelable(false);
builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps"));
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
if (isSessionClosed) {
BugSenseHandler.startSession(this);
isSessionClosed = false;
}
}
#Override
protected void onPause() {
super.onPause();
BugSenseHandler.closeSession(this);
isSessionClosed = true;
}
#Override
public void onBackPressed() {
map.clear();
super.onBackPressed();
}
private void retrieveLocation() {
Intent intent = getIntent();
address = intent.getStringExtra("location");
assert address != null;
if (address.equalsIgnoreCase("")) {
address = Utils.getCurrentLocation(LocationActivity.this);
}
rec_id = intent.getLongExtra("receipt_to_update_location", 0);
final Geocoder geocoder = new Geocoder(this, Locale.US);
double latitude = 0, longitude = 0;
try {
List<Address> loc = geocoder.getFromLocationName(address, 5);
if (loc.size() > 0) {
latitude = loc.get(0).getLatitude();
longitude = loc.get(0).getLongitude();
} else {
Utils.showToast(LocationActivity.this, getString(R.string.UnableToFindLocation), Toast.LENGTH_SHORT);
}
selectedLoc = map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(address).draggable(true));
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
try {
List<Address> addresses = geocoder.getFromLocation(selectedLoc.getPosition().latitude, selectedLoc.getPosition().longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getAddressLine(0) != null)
sb.append(address.getAddressLine(0)).append(", ");
if (address.getLocality() != null)
sb.append(address.getLocality()).append(", ");
if (address.getCountryName() != null)
sb.append(address.getCountryName());
}
address = sb.toString();
} catch (IOException e) {
}
}
});
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
} catch (IOException e) {
Log.e("IOException", e.getMessage());
Utils.showToast(LocationActivity.this, getString(R.string.c_unknownLocation), Toast.LENGTH_LONG);
}
}
public boolean isGoogleMapsInstalled() {
try {
getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
I see you implement the intent.putExtra after you get the extra! You should do the put in the activity that receives the location data and when you want to receive the data from the intent.extra you should do this:
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude= (double)extras.getDouble("lat");
longitude=(double)extras.getDouble("lon");
}