I want to get the value of Longitude and Latitude of my current locatoin when offline and save the current location to its database. Is it possible to get the longitude and latitude of the device when mobile data and wifi are off but the GPS is ON?
Just use this code. Make sure the user hasn't selected wifi only or network only option in his location setings. it has to be high accuracy or GPS only. This piece of code will work.
public class Location extends AppCompatActivity {
LocationManager locationManager;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
mContext=this;
locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
2000,
10, locationListenerGPS);
isLocationEnabled();
}
LocationListener locationListenerGPS=new LocationListener() {
#Override
public void onLocationChanged(android.location.Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
Toast.makeText(mContext,msg,Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume(){
super.onResume();
isLocationEnabled();
}
private void isLocationEnabled() {
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
else{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
}
}
The parameters of requestLocationUpdates methods are as follows:
provider: the name of the provider with which we would like to register.
minTime: minimum time interval between location updates (in milliseconds).
minDistance: minimum distance between location updates (in meters).
listener: a LocationListener whose onLocationChanged(Location) method will be called for each location update.
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add above permissions to manifest file for the version lower than lollipop and for marshmallow and higher version use runtime permission.
Related
I need to get user Location using location manager. I successfully use intent to start Settings.ACTION_LOCATION_SOURCE_SETTINGS. I turn on location but still cant't get location.
When i checked phone settings and turned on App Level Permissions my app it worked fine.But i don't want users to manually do that,how can they turn on locations once and have app level permission for the app also turned on
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
LocationRequest request = new LocationRequest();
request.setInterval(0);
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the
alert dialog
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EmployeeDashBoard.this,"You must turn on
Location",Toast.LENGTH_LONG).show();
startActivity(new Intent(EmployeeDashBoard.this,
LoginScreen.class));
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}else{
//listener that responds to location updates
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateEmployeeLocation(location);
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
}
location turned on but no location got
when i turn on app level permission it works.How can users do both at once
I assume you are asking for LOCATION_PERMISSION only in Manifest and not during run time.
After Android 6.0 (API level 23) , You have to ask permission during run time.
if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,Manifest.permission.READ_CONTACTS)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
The above code is to ask permission about READ_CONTACTS
Do some modification to above code and add it to your project, it should work.
Go through this Documentation.
My app uses users location and have fragments. In main activity this fragments changes.
But there is a problem here. I implement "Location Listener" interface to my fragment class, and drop the breakpoint in "onLocationChanged" event. And program never hit the breakpoint.
Why I can not reach the users location?
Here is my code:
public class NearestCoffeeVenueFragment extends Fragment implements LocationListener{
// GPS Variables
private LocationManager locationManager;
private Location lastLocation;
private String provider;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(location != null){
lastLocation = location;
Toast.makeText(getActivity(), getString(R.string.gps_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getActivity(),getString(R.string.gps_fail),Toast.LENGTH_SHORT).show();
cannotReachGpsWarning();
}
return inflater.inflate(R.layout.fragment_nearest_coffee_venue, container, false);
}
/** LocationListener Interface Functions
* */
#Override
public void onLocationChanged(Location location){
Toast.makeText(getActivity(),"Long: "+location.getLongitude()+" Lat:"+location.getLatitude(),Toast.LENGTH_LONG).show();
lastLocation = location;
}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText(getActivity(),getString(R.string.gps_enabled_provider)+provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText(getActivity(),getString(R.string.gps_disabled_provider)+provider,Toast.LENGTH_LONG).show();
}
/// warning messages and buttons setted from strings file.
private void cannotReachGpsWarning(){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.gps_disabled))
.setCancelable(false)
.setPositiveButton(getString(R.string.gps_enable),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showGPSOptions();
}
});
builder.setNegativeButton(getString(R.string.gps_disable),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGPSOptions(){
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
As I say, I don't see any toasts or anything else. The fragment's doesn't hit the breakpoint on "onLocationChanged" function. This means fragment can't reach location. And when fragment starts, I see "Can not reach location" error even the phone's location was on.
Did you enable location in the device for both sources GPS ans NETWORK? Currently in your code your'e asking for network provider, if this provider is disabled the method getLastKnownLocation will return null.
I have this problem, I using GPS from my app to get latitude and longitude,when I want to return to home Icon GPS always show from top of my Mobile device,how I can turn off it after return to home screen
my code.
public class doctorlocation extends Activity implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctorlocation);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
//txtLat = (TextView) findViewById(R.id.textview1);
//txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
latitude=location.getLatitude();
longitude=location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
Use this code on onPause() of that Activity.
#Override
protected void onPause() {
Log.i("onPause", "inside onPause");
super.onPause();
locationManager.removeUpdates(myLocationListener);//locationManager.removeUpdates(this) ;
locationManager = null;
}
Enabling and Disabling the GPS is in the hands of the user. You can show him a Dialog to inform him about disabling the GPS. Keep two buttons on the dialog in that case - one for "Settings" and another one for "ok" or "cancel".
public static void promptForGPS(
final Activity activity)
{
final AlertDialog.Builder builder =
new AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Disable GPS....Message here"
+ " Click OK to go to"
+ " location services settings to let you do so.";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
The best I have found is
onResume()
{
// Request for GPS Location
//location.requestLocationUpdates()
}
and
onPause()
{
// Remove location
// location.removeUpdates()
}
By calls removeUpdates() method it will stop GPS whenever your Activity is not in forground. This way you can stop GPS as well as it will stop draining your battery.
You need to tell the LocationManager that you no longer need location updates when your App enters into background, by using
locationManager.removeUpdates(this);
in your onPause() method.
You should also move your call to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
to onResume(); so that location updates will resume once you re-enter your App.
the method startSightManagement() is called twice throug my program, so i have two location Manager objects.
private void startSightManagement() {
String locationService = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(locationService);
// Get the GPS provider and request location updates
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 2000, 2, this);
// Obtain last known location and update the UI accordingly
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
sightManager = new SightManager(this);
// Set up the first sight
setSight();
}
my onPause() Activity with removeUpdates(this)-->This only removes one instance, how do i remove the other one??
protected void onPause() {
myLocationOverlay.disableMyLocation();
locationManager.removeUpdates(this);
locationManager=null;
// TODO Auto-generated method stub
super.onPause();
//Shutdown TTS everytime when activity is paused(Tolga)
if (mTts != null) {
mTts.stop();
}
// Unregister the proximity intent receiver. This also prevents the app from
// leaking when it is closed.
if (proximityIntentReceiver!=null) {
unregisterReceiver(proximityIntentReceiver);
}
}
Second problem is: app crashes when gps isnt enabled on start and i click yes when asked if gps should be enabled. when i remove these two lines everything works fine:
locationManager.removeUpdates(this);
locationManager=null;
here is the buildAlert method if gps isnt enabled on start:
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS ist deaktiviert. Standorteinstellungen anzeigen?")
.setCancelable(false)
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), ENABLE_GPS_SUB);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
How can you ensure a good GPS signal is found before allowing a button click which starts logging GPS locations?
Well, if you use the LocationManager-class and act upon the onLocationChanged(), it won't actually trigger until it's gotten a position.
Edit: Here's something you can try out.
Edit#2: D'oh, I actually misread the question. I'll leave my response though.
.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="#+id/mybutton1"
android:visibility="INVISIBLE"
android:layout_width="200dp"
android:layout_height="100dp"
android:text="MyButton1"
/>
</LinearLayout>
.java:
//Get the LocationManager & Button
final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final Button button = (Button) findViewById(R.id.mybutton1);
//Add the listener
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Remove the listener and make the button visible
locManager.removeUpdates(locationListener);
button.setVisibility(1);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Let me know if this works out for you!
To check for a GPS fix, you'll have to register a gpsstatus.listener and look at the GPS status and the timing in between updates.
Check out this link for how:
How can I check the current status of the GPS receiver?
You can use this code inside your button click to check the status of GPS.
LocationListener ll = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, ll);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.i("About GPS", "GPS is Enabled in your devide");
AlertDialog.Builder GPSON =new Builder(MyCardio.this);
GPSON.setCancelable(false);
GPSON.setMessage("GPS IS ON");
GPSON.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
GPSON.show();
} else {
AlertDialog.Builder GPSOFF = new Builder(MyCardio.this);
GPSOFF.setCancelable(false);
GPSOFF.setTitle("Connection Error");
GPSOFF.setMessage(" Please Enable Your GPS !");
GPSOFF.setPositiveButton("Ok",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// startActivity(new Intent(LoginActivity.this,MainMenuActivity.class));
}
});
GPSOFF.show();
}