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();
Related
UPDATED QUESTION - STILL NOT WORKING
I've changed the code.
Now, deactivateAlerts and activateAlerts are in the MainActivity.
Now, inside activateAlerts(), I'm instantiating a GPSListener for the GPS Provider:
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
gpsListener = new GPSListener(getApplicationContext());
} else if
Where the GPSListener is this:
public class GPSListener implements LocationListener {
private Context mCtx;
private Location cLoc;
private LocationManager mLocMan;
public GPSListener (Context ctx){
mCtx = ctx;
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public Location getLocation()
{
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return cLoc;
}
public void stop()
{
mLocMan.removeUpdates(GPSListener.this);
}
#Override
public void onLocationChanged(Location location) {
Log.i("UPDATING", "updating location");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
With the deactiveAlerts() function, I execute the instruction to remove the GPS updates:
if(gpsListener!=null){
gpsListener.stop();
}
But the GPS is not stopping yet =(
What is the problem now?
ORIGINAL QUESTION
The user can activate or deactivate location updates.
If the location updates are activated, it works ok, but when the location updates are deactivated, the GPS is still waiting for updates (and the icon appears on the action bar).
The code is that:
public class Alerts extends Fragment {
MyLocationListener myLocationListener = null;
...
public void activateAlerts() {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
} else {
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
}
}
});
...
}
public void deactivateAlerts() {
...
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
if(myLocationListener != null) {
locationManager.removeUpdates(myLocationListener);
myLocationListener = null;
}
...
}
public class MyLocationListener implements android.location.LocationListener {
public void onLocationChanged(Location location) {
Log.i("UPDATING", "updating location");
}
public void onStatusChanged(String s, int i, Bundle b) {
Log.v("LocationListener", "onStatusChanged");
}
public void onProviderDisabled(String s) {
Log.v("LocationListener", "onProviderDisabled");
}
public void onProviderEnabled(String s) {
Log.v("LocationListener", "onProviderEnabled");
}
}
What is the problem?
I've read this posts:
Post1
Post2
Post3
Post4
I have a code for detecting location that I want to works only for 2 minutes.
when I fire start() method script must works almost for 2 minutes.
problem is in there that how run my script only for an specific time.
I used this code but don't running correct.
don't fire stop() method from in Timer().schedule()
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
new Timer().schedule(
new TimerTask(){
public void run() {
stop();
}
}
,System.currentTimeMillis(), 2*60*1000);
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
lastloc = location;
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
Check your code of Timer again. Usually, the Timer code should be like:
Timer.schedule(TimerTask,
delayTime); // delay a task before executed for the first time, in milliseconds
Because of your delayTime has been executed by using System.currentTimeMillis(), the System picks the current time in milliseconds since midnight, so that the TimerTask will be executed after millions millisecond.
Hence, use this code:
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// do your thing here
}
}, 2*60*1000);
See this documentation about the type of Timer you created.
I finally solved my problem by using handlers.
read this page: Using Bundle Android to Exchange Data Between Threads
a.java
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
private Thread workingthread = null;
final Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
Log.d("states","return msg from timer2min");
if(msg.what==1){
stop();
}
super.handleMessage(msg);
}
};
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
workingthread=new timer2min(mHandler);
workingthread.start();
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
timer2min.java
public class timer2min extends Thread {
private Handler hd;
public timer2min(Handler msgHandler){
hd = msgHandler;
}
public void run() {
try {
Thread.sleep(2*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = hd.obtainMessage();
msg.what = 1;
hd.sendMessage(msg);
}
}
I´d like to implement a LocationListener in this way.
1 - Activity_first - Call LocationListener, but I have some spinner and this don´t respond when the LocationListener are onStart(). I´d like to implement with a Thread.
2 - When the onLocationChanged() in LocationListener gets called, I call Geocoder, and when the address is different than null, I save it on the shared preferences, and stop it.
Point 2, must be done in the background because the user might be in an Activity when I get the Geocoder's address (about 10 seconds, it depend on connection)
I was testing with IntentService, but of course, I doesn't work.
My Code
public class Carga_1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carga_1);
// Todo Create Spinner, etc
startService(new Intent(Carga_1.this, LocationService2.class));
}
}
public class LocationService2 extends Service {
public static final String BROADCAST_ACTION = "Hello World";
//public LocationManager locationManager; testted
//public MyLocationListener listener; tested
public Location previousBestLocation = null;
Thread my_thread;
#Override
public IBinder onBind(Intent intent) {
Log.d("[GPS_coord]", "????");
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
Runnable r = new Runnable() {
public void run() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}
};
my_thread = new Thread(r);
my_thread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
my_thread.stop();
}
private void get_address(double lat, double longi) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(lat, longi, 1);
//SAVE ON SharedPrefereces
this.stopSelf();
}
catch (IOException e) {
Log.d("[GPS_geocoder]", "Decodificacion Erronea");
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(final Location loc) {
Log.i("GPS_Service", "Location changed");
Log.d("GPS_Service", String.valueOf(loc.getLatitude() + " : " + String.valueOf(loc.getLongitude())));
get_address(loc.getLatitude(), loc.getLongitude());
}
public void onProviderDisabled(String provider) {
Log.i("GPS_Service", "DES_habilitado");
}
public void onProviderEnabled(String provider) {
Log.i("GPS_Service", "Habilitado");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Simply, I want to get current location and location changes through GPS via AsyncTask.
I have tried many ways out and also gone through many stuff related it, but cant help myself out. Here is my code, please suggest changes to make to the code.
public class MyGps extends Activity {
/** Called when the activity is first created. */
public static EditText txtLatitude;
public static EditText txtLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GpsAsyncTask gpsTask = new GpsAsyncTask(this, this);
gpsTask.execute(null);
}
}
public class GpsAsyncTask extends AsyncTask<String[], String, String> {
Context context;
Activity activity;
private LocationManager locationManager;
private Location currentLocation;
Double mlat, mlng;
public GpsAsyncTask(Activity act, Context ctx) {
context = ctx;
activity = act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
String provider = Settings.Secure.getString (context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
Toast.makeText(context, "Trying to connect GPS", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is not connected", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String[]... params) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0f, new LocationListener()
{
public void onLocationChanged(Location loc)
{
mlat=loc.getLatitude();
mlng=loc.getLongitude();
return;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
{
MyGps.txtLatitude.setText(Double.toString(mlat));
MyGps.txtLongitude.setText(Double.toString(mlng));
}
}
}`
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.