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();
}
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.
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.
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();
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();
}