I have a requirement to detect when the user of my app enters a new country. I am hoping there is some sort of listener that I can use and have considered detecting when the phone carrier changes and doing a quick check for current country in these instances.
Is there a better way of doing this?
I don't want to trigger a check each time the cell tower changes...Not only does this only work when the phone is awake, but it also probably happens quite often which wouldn't be ideal.
Add these permissions
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Create a class for GPS Tracking like GPSTracker.java
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Activity mActivity;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Activity mActivity) {
this.mActivity = mActivity;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("Enable GPS Settings For Accessing Camera");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mActivity.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
mActivity.finish();
}
});
alertDialog.show();
}
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
return addresses;
} catch (IOException e) {
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Now create a timer task or an infinite loop from a asynchronous task with a time delay and check for the country
public class MainActivity extends Activity {
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private static final String COUNTRY_KEY = "country_key";
private CountDownTimer mTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = getSharedPreferences(
MainActivity.this.getCallingPackage(), Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
final GPSTracker gpsTracker = new GPSTracker(this);
mTimer = new CountDownTimer(Long.MAX_VALUE,10 * 1000) {
#Override
public void onTick(long millisUntilFinished) {
if (gpsTracker.canGetLocation()) {
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(gpsTracker.latitude,
gpsTracker.longitude, 1);
if (addresses.size() > 0) {
String country = addresses.get(0).getCountryName();
if(mSharedPreferences.getString(COUNTRY_KEY, null) == null){
//This is the first entry
mEditor.putString(COUNTRY_KEY, country);
mEditor.commit();
}else{
String savedCountry = mSharedPreferences.getString(COUNTRY_KEY, null);
if(!savedCountry.equals(country)){
//Now the country has changed so do your stuff
Toast.makeText(MainActivity.this, "Country Has changed to " + country,
Toast.LENGTH_LONG).show();
//Also save the country to preferences if you want
//mEditor.putString(COUNTRY_KEY, country);
//mEditor.commit();
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
gpsTracker.showSettingsAlert();
}
}
#Override
public void onFinish() {}
};
mTimer.start();
}
}
Related
I have created a project sunshine which gives weathery detail by tracking your
current location it works fine but sometimes my GPSTracker class which returns me the latitude,longitude and postal code along with the country doesnt return the data at the time and then my app shows then the network error
I dont know whats the problem sometimes it works very fine but sometimes it doesnt.
My GPSTracker class:-
package com.example.na462.sunshine;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
GPSEnabled.GPS = isGPSEnabled;
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
int afl = ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION );
int acl = ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION );
if (locationManager != null) {
Log.d("locationManager",""+locationManager);
if (afl != PackageManager.PERMISSION_GRANTED && acl != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return location;
}
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != 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;
}
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;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle("Alert Title");
//Setting Dialog Message
alertDialog.setMessage("gpsmessage");
//On Pressing Setting button
alertDialog.setPositiveButton(0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton("cancle", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
*
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
return addresses;
} catch (IOException e) {
// e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
/**
* Try to get AddressLine
*
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
*
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
/**
* Try to get Postal Code
*
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
*
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And my Splash Activity where i am demanding for postal code and other stuff:
Note ValuetoPass,Coordinates and CordinateLoc are other classes in other activitites for passing the information i have used them
package com.example.na462.sunshine;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import static android.R.attr.animation;
import static com.example.na462.sunshine.R.id.MainList;
public class SplashActivity extends Activity implements Animation.AnimationListener {
Animation animation,TextAnimation;
Double Latitude;
Double Longitude;
String Country;
ImageView imageView;
ImageView ErrorImage;
TextView AnimationText;
Button ErrorReload;
LinearLayout Layout;
String PostalCode;
Receiver receiver;
boolean Connection;
GPSTracker gpsTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
AnimationText = (TextView)findViewById(R.id.TextAnimation);
ErrorReload = (Button)findViewById(R.id.ErrorReload);
imageView = (ImageView)(SplashActivity.this).findViewById(R.id.Animation);
Layout = (LinearLayout)findViewById(R.id.Error);
ErrorImage = (ImageView)findViewById(R.id.Nointernet);
gpsTracker = new GPSTracker(SplashActivity.this);
gpsTracker.getLocation();
receiver = new Receiver();
Connection = receiver.internetconnection(SplashActivity.this);
if(!Connection || !GPSEnabled.GPS){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.VISIBLE);
ErrorImage.setVisibility(View.VISIBLE);
AnimationText.setVisibility(View.INVISIBLE);
}
else {
AnimationText.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
Layout.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(SplashActivity.this, ScrollingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
}, 8000);
animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink);
TextAnimation.setAnimationListener(this);
AnimationText.startAnimation(TextAnimation);
new FetchGPS().execute();
}
}
private class FetchGPS extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... voids) {
Latitude = gpsTracker.getLatitude();
Longitude = gpsTracker.getLongitude();
Country = gpsTracker.getCountryName(SplashActivity.this);
PostalCode = gpsTracker.getPostalCode(SplashActivity.this);
CordinatesLoc.Latitude = Latitude;
CordinatesLoc.Longitude = Longitude;
CordinatesLoc.CLatitude = Latitude;
CordinatesLoc.CLongitude = Longitude;
CordinatesLoc.Country = Country;
Coordinates.Latitude = String.valueOf(Latitude);
Coordinates.Longitude = String.valueOf(Longitude);
CordinatesLoc.Postal = PostalCode;
ValuesToPass.Pincode = PostalCode;
ValuesToPass.Country = "in";
return PostalCode;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
// Its an onclick Method For Retry if there isnt any conncection or GPS Estabished
public boolean ErrorReload(View V){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.INVISIBLE);
AnimationText.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
gpsTracker.getLocation();
Connection = receiver.internetconnection(SplashActivity.this);
if(!Connection || !GPSEnabled.GPS){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.VISIBLE);
ErrorImage.setVisibility(View.VISIBLE);
return false;
}
AnimationText.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
Layout.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(SplashActivity.this, ScrollingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
}, 8000);
animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink);
TextAnimation.setAnimationListener(this);
AnimationText.startAnimation(TextAnimation);
new FetchGPS().execute();
return true;
}
}
I think you should check your manifest.mf file. Maybe you need to add a permission to locate your smartphone.
i think code works fine...sometimes GPS cannot track coordinates in buildings. best solution is to use fused location provider api
Class for getting Location
public class TrackGPS extends Service implements LocationListener {
private final Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public TrackGPS(Context mContext) {
this.mContext = mContext;
getLocation();
}
private Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
catch(SecurityException e){
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(TrackGPS.this);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle ) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
Code for Main Activity is
private static final int REQUEST_CODE_PERMISSION = 1;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION
private Button b_get;
private TrackGPS gps;
double longitude;
double latitude;
//----------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_get = (Button)findViewById(R.id.locationBtn);
b_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps = new TrackGPS(MainActivity.this);
if(gps.canGetLocation()){
longitude = gps.getLongitude();
latitude = gps .getLatitude();
Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
}
else
{
gps.showSettingsAlert();
}
}
});
if(Build.VERSION.SDK_INT>= 23) {
if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{mPermission,
},
REQUEST_CODE_PERMISSION);
return ;
}
else
{
}
}
protected void onDestroy() { super.onDestroy() gps.stopUsingGPS();
}
Add Required permissions in your manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
my application is using GPS services now i in case the GPS is off the user have the option to navigate to the device settings and set the GPS on.
now i would like to handle the user selection,
in case the user turn on the GPS the app should run again the getLocation function other wise do nothing.
but i do not know how can i handle the result of the new activity because i run it from non activity class. the relevant method is LocationAlertDialog
this is my class code:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating,tryLocating = true;
private LocationManager locationManager;
private Location currentLoc=null;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
listener.getLocationInProccess();
try {
locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on Settings and make sure your GPS is enabled");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tryLocating =false;
listener.onLocationFound(currentLoc);
dialog.cancel();
}
});
alertDialog.show();
}
/**
* this function get Longitude and Latitude coordinates and send back the real street address.
* #param LATITUDE
* #param LONGITUDE
* #param ctx
* #return
*/
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception", "error converting address");
ex.printStackTrace();
}
return p1;
}
public boolean isTryLocating() {
return tryLocating;
}
}
I have created an IntentService class which i used to send device data to a web service whether the app is running or is terminated. Here's my code:
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class PostMyCoordinatesService extends IntentService implements GPSTracker.GPSUpdateListener,WebService.WebServiceListener {
GPSTracker gpsTracker;
DataCacher dataCacher;
WebService webService;
private String TAG = Constants.GLOBAL_TAG+"-PostService";
public static final String SERVICE_NOTIFIER ="<mypackagename>";
public PostMyCoordinatesService(String name) {
super(name);
}
public PostMyCoordinatesService(){
super("PostMyCoordinatesService.");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v(TAG,"HANDLE INTENT IS CALLED!");
startMyLocationUpdates();
}
private void startMyLocationUpdates() {
//reset location update callbacks if it exists.
if (gpsTracker != null) {
gpsTracker.stopUsingGPS();
}
gpsTracker = null;
dataCacher = DataCacher.getInstance();
if(dataCacher== null)
dataCacher = new DataCacher(getApplicationContext());
String seekbarCachedValue = dataCacher.getStringForKey(Constants.KEY_FREQUENCYUPDATES);
boolean allowGPS = dataCacher.getBooleanForKey(Constants.KEY_ALLOW_DEVICEGPS, false);
if(allowGPS) {
gpsTracker = new GPSTracker(getApplicationContext(), (Integer.parseInt(seekbarCachedValue) + 60));
gpsTracker.setOnGPSUpdateListener(this);
Log.v(TAG,"Starting gps updates.");
}
else{
Log.v(TAG, "Sending gps data was disabled.");
}
}
#Override
public boolean stopService(Intent name) {
super.stopService(name);
if (gpsTracker != null) {
gpsTracker.stopUsingGPS();
Log.v(TAG,"GPS tracking was disabled");
}
return true;
}
#Override
public void onGPSUpdated(Location updatedLocation) {
dataCacher = DataCacher.getInstance();
if (dataCacher == null)
dataCacher = new DataCacher(getApplicationContext());
boolean allowGPS = dataCacher.getBooleanForKey(Constants.KEY_ALLOW_DEVICEGPS, false);
if (allowGPS) {
Log.v(TAG, "Updating my coordinates>.." + updatedLocation.toString());
sendMyLocation(updatedLocation);
}
}
private void sendMyLocation(Location location){
dataCacher = DataCacher.getInstance();
if(dataCacher==null)
dataCacher = new DataCacher(getApplicationContext());
//get phone number
String phoneNumber = dataCacher.getUserPhone();
String url =Constants.URL_POST_DEVICE_LOCATION+
phoneNumber+"/"+
location.getLatitude()+"/"+
location.getLongitude()+"/"+
location.getSpeed()+"/"+
location.getBearing()+"/"+
location.getAltitude();
Log.v(TAG,">>update my coordinates url: "+url);
webService = new WebService(url,this);
webService.execute();
}
#Override
public void didReceiveData(String data, WebService caller) {
Log.v(TAG, "Coordinate Update Service: " + data);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(SERVICE_NOTIFIER));
}
#Override
public void didReceiveError(String errorMessage) {
Log.v(TAG,"Coordinate Update Service ERROR: "+errorMessage);
}
}
my logcat shows that my handle intent has been called:
08-27 14:03:01.989 26460-26534/? V/Test-PostService﹕ HANDLE INTENT IS CALLED!
08-27 14:03:02.003 26460-26534/? V/Test-PostService﹕ Starting gps updates.
But the callback method onGPSUpdated(Location updatedLocation) wasn't called. I am certain of my GPSTracker class' callbacks for I have used it on my previous projects. What could be the cause of this? What is the more efficient way to send updates to web service for both my app's running and terminated status. I am new to Service by the way. Any help would be greatly appreciated.
EDIT:
Here's my GPSTracker class.
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener{
public interface GPSUpdateListener {
void onGPSUpdated(Location updatedLocation);
}
String TAG = Constants.GLOBAL_TAG+"-GPSTracker";
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; //meters
// The minimum time between updates in milliseconds
private static long MIN_TIME_BW_UPDATES = 1000*60; //default 60 secs
// Declaring a Location Manager
protected LocationManager locationManager;
//snarf added variables
private static GPSTracker trackerInstance;
//snarf added methods
private GPSUpdateListener listener;
public void setOnGPSUpdateListener(GPSUpdateListener updateListener){
listener = updateListener;
}
public static GPSTracker getTrackerInstance(){
return trackerInstance;
}
public GPSTracker(Context context, int updateIntervalSeconds) {
this.mContext = context;
MIN_TIME_BW_UPDATES = updateIntervalSeconds * 1000;
Log.v(TAG,"starting location updates every "+MIN_TIME_BW_UPDATES+ " milliseconds.");
getLocation();
trackerInstance =this;
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
}
return location;
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
if(listener!=null)
listener.onGPSUpdated(location);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
Log.v(TAG,"Stopped gps updates!");
}
}
}
I'm Developing an application to send User's current location on selected contact number when user long presses power key button while the device is actually locked as pattern/screen lock mode. so how can i enable GPS so that it gets auto enable and gets current longitude and latitude.
First, you need to take care of the key press, and there is some good information here.
Here is an example of getting longitude and latitude:
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}