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();
Related
I have a simple App which currently simply asks for necessary permissions and in case GPS is OFF, you get an AlertDialog asking you if you want to switch it ON. After accepting, being taken to GPS options, enabling it, and going back to my App, I'd like to update location and here I get lost.
In other words, I'm trying to do what's stated here: https://stackoverflow.com/a/43396965/7060082
Unfortunately I can't manage to get it done and the example is a bit complicated for me to understand. Here is a piece of my code showing the relevant bits:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
private void getLatLon() {
//manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = manager.getBestProvider(criteria, false);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
manager.getLastKnownLocation(provider);
if (location != null) {
Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();
} else {
// manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
//location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
*/
}
}
}
#Override
public void onLocationChanged(Location l) {
location = l;
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
}
After asking for ACCESS_FINE_LOCATION permission (which is also stated on the manifest) I call checkGPS(). As said before, let's you enable or not the GPS. If enabled, I call getLatLon(). If there is a lastKnownLocation, good, if not...
Here I get lost. I call requestLocationUpdates and then do nothing waiting for onLocationChanged to recieve a location update and execute the rest of the code. Am I doing it right? The result is me clicking the button, switching GPS on. Click on the button again and nothing happens.
Any help with this will help.
Many thanks for your time.
I've developed fused location api demo application and utility pack here.
General Utilities
Try it if useful for you. To get location using fused location api, you just have to write following snippet...
new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
And if you want to customise it, simply find documentation here...
https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler
I've written a sample code according to your need, this will handle GPS enable/disable dialog internally, try this one...
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.Marker;
import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;
/**
* Lets see how to use utilities module by implementing location listener.
*
* #author Khan
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Marker marker;
private LocationHandler locationHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtaining an instance of map
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.locationHandler = new LocationHandler(this)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(10000)
.setLocationListener(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.locationHandler.start();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (marker == null) {
marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
} else {
marker.setPosition(latLng);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationHandler != null) {
locationHandler.stop();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LocationHandler.REQUEST_LOCATION) {
locationHandler.start();
}
}
}
Hope it will help you.
Your current code doesn't wait for the user to make a choice before calling getLatLon() in the case where GPS is disabled.
You will need to add a onActivityResult() override that will be called when the user goes back to your app.
First, remove the call to getLatLon() in the checkGPS() method for the case where GPS is disabled:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
//Remove this:
//getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
Then, add the onActivityResult() override, check the setting again, and if it's now enabled then call getLatLon():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLatLon();
}
}
after some time busy with other projects, got back to this one and I removed the getLatLon(); function from the checkGPS(); function and that's it, code is fine. I was using the emulator to check if this was working, but I forgot that the emulator has a fixed value for the latitude and longitude, so you get no updates like a real mobile phone, and thus it looked as if it was not working properly.
Sort of a newby mistake. Regardless, thanks for your offers. Was interesting looking at different ways of doing the same thing.
Sartox
I have created a custom layout for my alertdiaog : alertdialog.setView(inflater.inflate(R.layout.custom_gps,null));
I want to replace the default Ok and cancel buttons with my buttons, since it's not possible to use findViewById in a service class, I wanted to know if there is a workaround to handle the clicks on my custom buttons.
I took a look at some old questions but i did not find (yet) any trick to make that happen. Can you guys help ?
I have another workaround on my mind, and it is to extend Activity instead of Service (whice will make findViewByID available, but what changes do i have to apply on my class to start a Service from an activity ?
Any help or indication is welcome !
public class GPSTracker extends Service implements LocationListener {
private final Context mcontext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude,longitude;
private Button ok_button,cancel_button;
//the minimum distance to change updates in meters :
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
//the minimum time between updates (milliseconds) :
private static final long MIN_TIME_BETWEEN_UPDATE = 600000; // 10min
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_BETWEEN_UPDATE,
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();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationmanager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BETWEEN_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationmanager != null) {
location = locationmanager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/*
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 if gps is enabled
* #return boolean
*
*/
public boolean canGetlocation(){
return this.canGetLocation;
}
/*
function to show settings alert.
*/
public void showSettingsAlert(){
AlertDialog.Builder alertdialog = new AlertDialog.Builder(mcontext);
LayoutInflater inflater = LayoutInflater.from(mcontext);
inflater = (LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alertdialog.setView(inflater.inflate(R.layout.custom_gps,null));
/*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);
}
});
// on pressing cancel button
/* 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);
}
}
}
You can create a simple class in which you have a method which show the dialog and you need to call that method very simple.ex-
public class AlertDialog {
public static void showdialog(Context context) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
now in your service you can directly call this method by passing the context.
like-
AlertDialog.showdialog(context);
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.
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 have a problem with setting GPS service . I want to check if GPS is enable . If it is disable , it will display a dialog to user turn it on . The problem is it not wait for user enable GPS and get location .
I have a class
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_FOR_UPDATE = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context ctx) {
this.mContext = ctx;
getLocation();
}
public Location getLocation()
{
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable)
{
showSettingsGPSAlert();
}
else if(!isNetworkEnable)
{
showSettingsNetWorkAlert();
}
else
{
this.canGetLocation = true;
if(isNetworkEnable)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnable) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}catch (Exception ex)
{
Log.e("<<Location Error>>",ex.getMessage());
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public boolean canGetGPS() {
return this.isGPSEnable;
}
public boolean canGetNetwork() {
return this.isNetworkEnable;
}
public void showSettingsGPSAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startService(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void showSettingsNetWorkAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("NetWork is settings");
// Setting Dialog Message
alertDialog.setMessage("NetWork is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#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) {
}
}
And I have class to use it
public class RestaurantListFragment extends ListFragment {
private ArrayList<Restaurant> restaurants;
private SQLDataHelper dataHelper;
private GPSTracker gps;
private double UserLatitude;
private double UserLongitude;
private ProgressDialog progressBar;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.restaurant_list, null);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gps = new GPSTracker(getActivity());
UserLatitude = gps.getLatitude();
UserLongitude = gps.getLongitude();
Toast.makeText(getActivity(),UserLatitude + "|" + UserLongitude,Toast.LENGTH_SHORT).show();
dataHelper = new SQLDataHelper(getActivity(), "restaurantDB");
restaurants = new ArrayList<Restaurant>();
dataHelper.openDB();
Cursor cursor = dataHelper.query("Restaurant", new String[]{"Id", "ResName", "Logo", "Address", "Latitude", "Longitude"}, null
, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Restaurant restaurant = new Restaurant();
restaurant.setId(cursor.getInt(0));
restaurant.setResName(cursor.getString(1));
restaurant.setLogo(cursor.getString(2));
restaurant.setAddress(cursor.getString(3));
restaurants.add(restaurant);
} while (cursor.moveToNext());
}
//Collections.sort(restaurants);
RestaurantAdapter restaurantAdapter = new RestaurantAdapter(getActivity(),restaurants);
setListAdapter(restaurantAdapter);
}
}
It works fine when GPS is enable . I want the user can turn it on first . After that it show user location . Then it can query database and setListAdapter . Thanks for any suggestion .