I have a service for listening the GPS locations and I want to display an updated location in Toast, I run the service in other activity by clicking a Button. The service is created successfully but not showing the toast of updated location. Here is code:
public class locationlistening_service extends Service implements LocationListener {
static LocationManager locationManager;
LocationListener locationListener;
private static final String TAG = "Calculations";
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
run();
}
private void run(){
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
//Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
recordLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
}
public void recordLocation(Location loc)
{
Toast.makeText(locationlistening_service.this,"Lat: " + String.valueOf(loc.getLatitude()) + " Long: " + String.valueOf(loc.getLongitude()),Toast.LENGTH_SHORT).show();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
there is call of service in other activity.
public void startButton(View view) {
startService(new Intent(this, locationlistening_service.class));
}
You are never calling requestLocationUpdates(). Hence, nothing is using your LocationManager, LocationListener, or Criteria.
Please be sure to shut down this service when it is no longer needed.
Related
There is any solution to check if user disable GPS in settings?
I open my app, open top toolbar of android system, disable GPS and close this toolbar. In this moment I want to app check if status of GPS was changed.
I use check if GPS is active in onResume(), but this solution works only when user enable GPS, when disable onResume() is not called.
Any ideas?
Edit:
This is may class:
public class PrivacyActivity extends BaseActivity implements GpsStatus.Listener, LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Toast.makeText(this, "ads", Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(this, "ads1", Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
}
and when I disable gps I didn't see toast.
You can use the LocationListener class
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Log.i("Example", "GPS is ON");
}
public void onProviderDisabled(String provider) {
Log.i("Example", "GPS is OFF");
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You can get more info in http://developer.android.com/guide/topics/location/strategies.html
Reference the locationListener first.
LocationListener locationListener;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng myPlace = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(myPlace).title("me"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPlace));
mMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
onProviderDisabled method will be fired if the user has disabled GPS from settings.
The intent inside the method will take the user to location settings directly.
Tested and works fine.
i need to get the lat and lon in a activity. In my oncreate method I tried the code below but im not getting anything when i try to print the Lat. What am I doing wrong. I have included in the manifest file too. I need two strings with the value of Lat and lon
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener lis = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("", "location " + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lis);
I am trying to make an app where an intent service is running in the background and getting the location of the user by the network provider, and when the user is close to his destination(a phone-call gate) its starts another IntentService for the specific gate and get location updates more often by the gps provider.
Problem is when I try to get the location on the more active intentservice it doesn't respond at all.
here is the code in my onStartCommand:
Bundle gateData = intent.getExtras();
gateLat = gateData.getDouble("latitude");
gateLong = gateData.getDouble("longitude");
gateName = gateData.getString("gateName");
gatePhoneNumber = gateData.getString("gatePhoneNumber");
gateId = gateData.getInt("gateId");
Log.i("Active onStartCommand for:", gateId+"\n"+gateName+"\n phone:"+gatePhoneNumber);
helper = new MyGatesOpenHelper(this);
currentGate = helper.getGate(gateId);
currentGate.setMode(Gate.MODE_ONHOLD);
helper.updateGate(currentGate);
results = new float[3];
aManager = (LocationManager)getSystemService(LOCATION_SERVICE);
aListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
makeUseOfNewLocation(location);
Log.i("onLocationChanged coords","Lat:"+location.getLatitude()+" Long:"+location.getLongitude());
}
};
boolean isGpsEnabled = aManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("GPS Status:",isGpsEnabled?"Enabled":"Disabled");
aManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, aListener);
return super.onStartCommand(intent, flags, startId);
I want after open dialog and click on location button, detect user's location and show user's location and then user dismiss dialog, location listener removes and not get location from onLocationChanged, I try used locationManager.removeUpdate(locListener)on override dismiss but not any chance and location after dismiss again shows! why? How can i detect user's location after show dialog and after detect location, location listener remove? Thanks
EDIT:
public class DialogTest extends Dialog implements
android.view.View.OnClickListener {
Context context;
LocationManager locationManager;
LocationListener locationListener;
Location location;
public DialogTest(Context context) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.context = context;
setContentView(R.layout.profile_dialog);
getWindow().setBackgroundDrawableResource(R.drawable.background_dialog);
firstAccessLocation=true;
setCancelable(true);
initialize();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
findAddress();
}
private void findAddress() {
// if (gpsCheckBox.isChecked()) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// }
}
private void stopTracking(){
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
#Override
public void dismiss() {
// TODO Auto-generated method stub
stopTracking();
gpsTurnOff();
super.dismiss();
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(location!=null)
Log.e("location", location.getLatitude()+"");
location = loc;
if (location != null&& firstAccessLocation) {
setAddress(location.getLatitude(), location.getLongitude());
firstAccessLocation=false;
}
Toast.makeText(context, "changed", Toast.LENGTH_LONG).show();
Log.e("location", "changed");
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
In new code you should use LocationClient rather then LocationManager. It's more efficient in getting the location with minimal energy(battery drain) with greater accuracy. Look here LocationClient vs LocationManager. With LocationClient established you can call getLastLocation() which provide you last location and doesn't start cyclic location updates.
If you want to stick with LocationManager use requestSingleUpdate (String provider, LocationListener listener, Looper looper) method to get only one newest location from it.
In my application i want to get the updated location of the mobile user and i want to send it to the server continuously after periodic interval of certain time or after the user travels certain(say 500 meter) distance.I need these things to be done in backgroung.I know for this i have to implement service class. But I am not getting exactly how to do this.I did some work on that.
Can anybody please help me in this issue.
I did following things in the service class.
public class BackGroundService extends Service implements LocationListener{
public static final String Tag = BackGroundService.class.getName();
LocationManager myLocationManager;
Location myLocation;
LocationListener myLocationListener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void OnCreate()
{
super.onCreate();
Log.d(Tag, "Service Started");
android.os.Debug.waitForDebugger();
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_LOW);
String locationProvider = myLocationManager.getBestProvider(criteria, true);
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 500, myLocationListener);
myLocation = myLocationManager.getLastKnownLocation(locationProvider);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
longitude = location.getLongitude();
latitude = location.getLatitude();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Provider is disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Location Provider is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
From here I want know how can i get current lat/long of user and send it to the server.
Answer for my question is.......
public class LocationService extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final LocationManager mlocmag = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener mlocList = new MyLocationList();
final Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
UpdateWithNewLocation(loc); // This method is used to get updated location.
mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocList);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
private void UpdateWithNewLocation(final Location loc) {
// TODO Auto-generated method stub
if(loc!= null)
{
final double lat =loc.getLatitude(); // Updated lat
final double Long = loc.getLongitude(); // Updated long
ConnectMySQL obj = new ConnectMySQL();
obj.call(lat,Long); // Call this method when location is updated and save the data.
}
else
{
String latLongStr = "No lat and longitude found";
Toast.makeText(this, "Your location is "+latLongStr ,Toast.LENGTH_LONG).show();
}
}
public class MyLocationList implements LocationListener
{
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
UpdateWithNewLocation(arg0);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS Disable ", Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS enabled", Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}