can anyone guide on how to check internet connection setting with condition? I need something similar to this set of code.
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Below is my code and I would like to replace GPS checking into internet connection checking.
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource{
private GoogleMap map;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gpsIsEnabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000L, 10F, this);
else if(networkIsEnabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000L, 10F, this);
}
setUpMapIfNeeded();
}
//after user install/update Google Play Service, user might return to this activity
//to stop or resume the activity, onPause and onResume is needed
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
if(locationManager != null)
{
map.setMyLocationEnabled(true); //detect current location
}
}
you can use something like this..
public boolean isOnline(final Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
Builder dialogb = new AlertDialog.Builder(context);
if (netInfo != null && netInfo.isConnected()) {
return true;
}
dialogb.setTitle("No Internet.. :(");
dialogb.setMessage("We need internet to work. Kindly switch it on.");
dialogb.setPositiveButton("Turn on", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_WIRELESS_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialogb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialogb.show();
return false;
}
Related
I have an app where I need to get user's location. So at the start of the app, i have checked if the GPS is turned on or not. If yes, the user will easily log in to the app. If not, the alert dialog will be shown where user will be asked to turn it on. If the user denies, the app will close, if the user accepts to turn on gps, the user will be navigated to location settings. However, i am unable to track if the user has turned the gps on or not after the user reaches location settings. How do i do that ? This is my alert box code:
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog dialog = new AlertDialog.Builder(login.this).setTitle("GPS NOT ENABLED!")
.setMessage("Plese, turn on your gps to login to the app")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
dialog.dismiss();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK &&
event.getAction() == KeyEvent.ACTION_UP &&
!event.isCanceled()) {
dialog.dismiss();
finish();
return true;
}
return false;
}
})
.show();
dialog.setCanceledOnTouchOutside(false);
}
One way I have implemented in below fashion.
1.Create an interface:
public interface GpsInterface {
void onGpsStatusChanged(boolean gpsStatus);
}
2.Create a BroadcastReceiver:
public class GpsListener extends BroadcastReceiver {
private GpsInterface gpsInterface = null;
private Context context;
public GpsListener(){}
public GpsListener(Context ctx, GpsInterface gpsInterface){
this.gpsInterface = gpsInterface;
this.context = ctx;
}
#Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
gpsInterface.onGpsStatusChanged(true);
}else{
gpsInterface.onGpsStatusChanged(false);
}
}
}
3.Implement the GpsInterface in your class/activity
public class MyActivity extends Activity implements GpsInterface{
private GpsListener gpsListener;
private boolean isGpsOn;
//other stuff
}
//in onCreate()
IntentFilter mfilter = new IntentFilter(
"android.location.PROVIDERS_CHANGED");
gpsListener = new GpsListener(getActivity(), this);
registerReceiver(gpsListener, mfilter);
Implement the onGpsStatusChanged() method in the activity
#Override
public void onGpsStatusChanged(boolean gpsStatus) {
Logger.e("GPS STATUS", "ON " + gpsStatus);
isGpsOn = gpsStatus;
}
4.Unregister your broadcast receiver in onDestroy()
#Override
public void onDestroy() {
unregisterReceiver(gpsListener);
}
Hope this will help.
Use the below code to check whether gps provider and network providers are enabled or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
Here is a clean way to check GPS status during runtime.
Create a Broadcast Receiver
private BroadcastReceiver mGPSConnectivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// GPS ON
} else {
// GPS OFF
}
}
};
Register the Broadcast Receiver in onStart()
#Override
protected void onStart() {
super.onStart();
registerReceiver(mGPSConnectivityReceiver,
new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
Don't forget to unregister the Receiver in onStop()!
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mGPSConnectivityReceiver);
}
This is probably the easiest and cleanest solution for this problem. I really hope that it helps!
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);
I cannot seem to get my current location. In the second half of this dialog I call a class called MyLocation. I have never had any trouble with this class before. Now I have tried several differnt approachs to no avail. But I do beleive my trouble is with the context.
This is the first time using this in an AlertDialog in a Fragment. I think its this line giving me trouble.
myLocation.getLocation(context, locationResult);
I define context in my public View onCreateView
context = getActivity().getApplicationContext();
The alert is working as intended just the public void gotLocation does not seem to be getting called.
public void showLocationDialog() {
new AlertDialog.Builder(this.getActivity()).setItems(C,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
if (i == 0) {
LayoutInflater inflater = LayoutInflater
.from(getActivity());
final View textenter = inflater.inflate(
R.layout.dialog_location, null);
final EditText userinput = (EditText) textenter
.findViewById(R.id.etLocation);
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setView(textenter).setTitle(
"Enter Location or where abouts");
builder.setPositiveButton("Set",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog, int id) {
if (userinput != null){
tvLocation.setText(userinput.getText().toString());
dialog.cancel();
} else {
dialog.cancel();
showLocationDialog();
Log.e("NULL", "Dismiss");
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
} else if (i == 1) {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// Got the location!
location.getLatitude();
location.getLongitude();
String loc = location.getLatitude() + ","
+ location.getLongitude();
etLocation.setText(loc);
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(context, locationResult);
}
}
}).show();
}
MyLocation:
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Link your fragment with your dialog.
In YourFragment.java:
public class YourFragment extends Fragment {
YourFragment mYourFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
mYourFragment = this;
...
}
}
In YourDialog.java:
public class ClearDialogModern extends DialogFragment {
YourFragment mContent;
...
public void setContent(YourFragment content) {
mContent = content;
}
On creation of YourDialog:
newYourDialog = new YourDialog();
newYourDialog.setContent(mContent);
How to getLocation from YourFragment.java inside YourDialog.java:
mContent.getLocation();
I have a class for get the user location.
If the GPS is off I turned it on and show the location, but it doesnt work.
this is the class:
public class UseGPS implements Runnable{
Activity activity;
Context context;
private ProgressDialog pd;
LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
public UseGPS(Activity Activity, Context Context){
this.activity = Activity;
this.context = Context;
}
public void getMyPos(){
DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity,"no gps signal",Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
}
};
pd = ProgressDialog.show(activity,context.getString(R.string.looking_for), context.getString(R.string.gps_signal), true, true, dialogCancel);
writeSignalGPS();
}
private void setCurrentLocation(Location loc) {
currentLocation = loc;
}
private void writeSignalGPS() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
mLocationManager.removeUpdates(mLocationListener);
if (currentLocation!=null) {
Toast.makeText(activity,currentLocation.getLatitude(),Toast.LENGTH_LONG).show();
Toast.makeText(activity,currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}
};
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
setCurrentLocation(loc);
handler.sendEmptyMessage(0);
}
}
#Override
public void onProviderDisabled(String provider) {
/*turn on GPS*/
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
The code works when the GPS is turned on, but it doesnt turn the gps on.
What can I do?
While launching time of your app, give one pop-up message with option to turn on the GPS by the user.
This pop-up button navigates to GPS setting in Setting for their user can turn on the GPS.
Here is the code snippet:
AlertDialog gpsonBuilder = new AlertDialog.Builder(Home_Activity.this);
gpsonBuilder.setTitle("Your Gps Provider is disabled please Enable it");
gpsonBuilder.setPositiveButton("ON",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
gpsonBuilder.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 .