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.
Related
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.
Im experimenting with android development, and getting the location of a device.
my GPSTracker class is listed below with the error being thrown.
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;
/**
* Created by informationservices on 29/08/14.
*/
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; //latitude variable
double longitude; //longitude variable
//The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MIN_TIME_BW_UPDATES = 1000;
//declare location manager
protected LocationManager locationManager;
public GPSTracker(Context context){
this.mContext = context;
getLocation();
}
//function to get latitude
public double getLatitude(){
if (location != null){
latitude = location.getLatitude();
}
//must have a return (as its a function)
return latitude;
}
public double getLongitude(){
if (location !=null){
longitude = location.getLongitude();
}
return longitude;
}
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);
if(location !=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return location;
}
//check if this is the best network provider
public boolean canGetLocation(){
return this.canGetLocation;
}
//show GPs settings in alert box
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog(mContext);//AlertDialog(android.content.Context) has protected access in 'android.app.AlertDialog'
//set alert title
alertDialog.setTitle("GPS is Settings");
//set Dialog message
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.startActivities(new Intent[]{intent});
}
});
alertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
//show alert
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my first attempt at coding for android. I have been googling for a while, but can't see why it is throwing this error.
Could someone please explain what this error means, and how to fix it.
a thorough explication, and link to any relevant google docs would also be appreciated.
The error means that the AlertDialog constructor is not accessible (public). It is declared protected so the programmers are forced to use a builder pattern when working with AlertDialogs.
To show an AlertDialog, you use the AlertDialog.Builder to set everything up and then call show() to build and show the AlertDialog.
// Use the AlertDialog.Builder to configure the AlertDialog.
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(this)
.setTitle("GPS is Settings")
.setMessage("GPS is not Enabled. Do you want to go to settings menu?")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivities(new Intent[]{intent});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Show the AlertDialog.
AlertDialog alertDialog = alertDialogBuilder.show();
I counterd this problem because just now i was going to learn about the difference
between AlertDialog.Builder and AlertDialog so when i wrote
AlertDialog dialog=new AlertDialog();
so it gave me the same problem like yours
but since you wrote
AlertDialog.Builder alertDialog = new AlertDialog(mContext);
//.Builder was missing
AlertDialog.Builder = new AlertDialog.Builder(mContext)
and if you want to use AlertDialog then do it like this
AlertDialog = new AlertDialog.Builder(mContext)
This should work.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(
MapActivity.this);
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.setNegativeButton("cancel", null);
dialogBuilder.setCancelable(false);
dialogBuilder.setView(saySomething);
final AlertDialog mAlertDialog = dialogBuilder.create();
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
// To close once you are done with your operation call below method.
// mAlertDialog.dismiss();
}
});
}
});
mAlertDialog.show();
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();
}
i want to build an app in which users can make foto which is tagged with the current location of the phone. So after making a foto, the user can save the picture by touching on the "save" button. If the button is touched the current location will be determined with my own LocationListener class. The Listener-class shows a Progressdialog and dismiss it, after a location is found. But now i want to know which i can return the location back to the calling Activity, because the Location listener methods are callback methods. Is there a "best-practice" solution for that, or have anybody a clue?
Location Listener:
public class MyLocationListener implements LocationListener {
private ProgressDialog progressDialog;
private Context mContext;
private LocationManager locationManager;
public MyLocationListener(Context context, ProgressDialog dialog) {
mContext = context;
progressDialog = dialog;
}
public void startTracking() {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 10, 10, this);
progressDialog.show();
}
private void finishTracking(Location location) {
if(location != null) {
locationManager.removeUpdates(this);
progressDialog.hide();
Log.i("TRACKING",location.toString());
}
}
#Override
public void onLocationChanged(Location location) {
finishTracking(location);
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
Calling code:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Determine position...");
new MyLocationListener(this, dialog).startTracking();
Why not pass your own callback from activity to MyLocationListener and call its method from finishTracking?
Its a commonly used delegation pattern. Something like that:
class MyLocationListener implements LocationListener {
public interface MyListener {
void onLocationReceiver( Location location );
}
private MyListener listener;
public MyLocationListener(Context context, ProgressDialog dialog, MyListener listener) {
mContext = context;
progressDialog = dialog;
this.listener = listener;
}
private void finishTracking(Location location) {
if(location != null) {
locationManager.removeUpdates(this);
progressDialog.hide();
Log.i("TRACKING",location.toString());
listener.onLocationReceiver(location);
}
}
}
and call:
new MyLocationListener(this, dialog, new MyLocationListener.MyListener() {
public void onLocationReceived( Location location ) {
text.setText(location.toString());
}
}).startTracking();
You can do another simple thing - put your class MyLocationListener inside your Activity itself and modify the field in your activity inside your MyLocationListener itself.