I'm writing an app that requests for location updates like this:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, 0, locationListener);
onLocationChanged gets invoked when device is on but when put into sleep it stops receiving further updates. I followed this thread but as I said - it doesn't work.
The listener is registered inside foreground service that needs to work all the time. I want to conserve battery by waking it from sleep only when I receive new location.
EDIT: of course everything works when I acquire wakelock in onCreate() method and release it in onDestroy() method for service but I don't want to do this.
If you want to use background task then use this service
public class LocationFinder extends Service {
public static double lat, lng;
LocationManager locationManager;
public void onDestroy() {
super.onDestroy();
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
}
#Override
public void onCreate() {
Log.v("location", "===>location ed onCreate " + lat);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("location", "===>location ed onStartCommand " + lat + "==>" + lng);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getLocation();
}
});
return START_STICKY;
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void getLocation() {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
if (locationManager != null) {
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 500, 50, locationListener);
} else {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 500, 50, locationListener);
}
}
}
}
private void updateWithNewLocation(Location location) {
if (location != null) {
Log.v("location", "===>location ed " + lat);
lat = location.getLatitude();
lng = location.getLongitude();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Related
One of my android app needs to get gps positions, if the app is in destroy state. My app get gps positions currently when it is in running(active) and pause(background) modes. But when I destroyed my app, the service is running but the LocationListener onLocationChanged(Location location) not calling. How can I deal this type of issues?.
public class LocationFinder extends Service {
public static double lat, lng;
LocationManager locationManager;
public void onDestroy() {
super.onDestroy();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("location", "===>location ed onStartCommand " + lat + "==>"
+ lng);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
getLocation();
}
});
return START_STICKY;
}
final LocationListener locationListener = new LocationListener() {
// this method is not called when we destroyed the app. i want to call this method even app is in destoyed.
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
Toast.makeText(
getApplicationContext(),
"Location Finder : onLocation Changed "
+ location.getLatitude() + " "
+ location.getLongitude(), Toast.LENGTH_LONG)
.show();
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
public Location getLocation() {
Variables.writeLog("Enter into getLocation : \n", false);
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Location location = null;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
Log.v("Location", "Before");
if (locationManager != null) {
String provider = locationManager.getBestProvider(criteria, true);
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (provider != null) {
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 0,
locationListener);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 0,
locationListener);
if (location != null) {
updateWithNewLocation(location);
} else {
location = locationManager
.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider,
10, 0, locationListener);
}
} else {
location = locationManager
.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 10, 0,
locationListener);
}
} else {
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 10, 0,
locationListener);
}
} else {
if (locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 0,
locationListener);
} else if (locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10, 0,
locationListener);
} else if (locationManager
.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER, 10, 0,
locationListener);
}
}
}
return location;
}
private void updateWithNewLocation(Location location) {
if (location != null) {
Log.v("location", "===>location ed " + lat);
lat = location.getLatitude();
lng = location.getLongitude();
Variables.writeLog("Lat :" + lat + " lng : " + lng, false);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Hey you need to create background Service which will work in the background and do that job for you check those links
link 1
link 2
You can start this services when your activity is destroyed and the stop it when your app is resumed
You Have to run background service which will recieve locations using gps.
public class AndroidLocationServices extends Service {
WakeLock wakeLock;
private LocationManager locationManager;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
new ToggleGPS(getApplicationContext()).turnGPSOn();
// Toast.makeText(getApplicationContext(), "Service Started",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
if (isConnectingToInternet(getApplicationContext())) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
jsonObject.put("latitude", location.getLatitude());
jsonObject.put("longitude", location.getLongitude());
jsonArray.put(jsonObject);
Log.e("request", jsonArray.toString());
new LocationWebService().execute(new String[] {
Constants.TRACK_URL, jsonArray.toString() });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#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
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
new ToggleGPS(getApplicationContext()).turnGPSOff();
wakeLock.release();
}
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
I found this code in github. it works , I have used it in my appilcation.
GITHUB LINK
I'm trying to program an application which is using the current location from the user and calculating the distance and writes it into my listview.
The location doesn't have to be very accurate and i only want to fetch a new location when the list is refreshed or on app start, not continously.
My problem is that the locationlistener with gps takes too long to find a location and i have to update my list a lot before it is showing the right distance.
I was thinking about implementing a background task which gets the location and updates the list automatically when it found the position. Would that be a solution?
Is there any option to get a location faster, even if it is not as accurate as gps?
what i have so far on my location listener:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
myLoc.setLatitude(lat);
myLoc.setLongitude(lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
in this method i'm calling the locationmanager and listener and creating the listview with the distance
public void getList(){
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
//... creating the list with distance and so on
}
i hope you can give me some hints how i can implement this that i will work as described above or tell me what i should use instead.
thanks :)
1). You can use LocationManager.NETWORK_PROVIDER
This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
eg:- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
2). If you want to use background task then use this service
public class LocationFinder extends Service {
public static double lat, lng;
LocationManager locationManager;
public void onDestroy() {
super.onDestroy();
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
}
#Override
public void onCreate() {
Log.v("location", "===>location ed onCreate " + lat);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("location", "===>location ed onStartCommand " + lat + "==>" + lng);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getLocation();
}
});
return START_STICKY;
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void getLocation() {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
if (locationManager != null) {
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 500, 50, locationListener);
} else {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 500, 50, locationListener);
}
}
}
}
private void updateWithNewLocation(Location location) {
if (location != null) {
Log.v("location", "===>location ed " + lat);
lat = location.getLatitude();
lng = location.getLongitude();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So I am getting the longitude and latitude as:
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude=location.getLongitude();
latitude=location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Or use LocationManager.GPS_PROVIDER
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation!=null){
longitude=lastKnownLocation.getLongitude();
latitude=lastKnownLocation.getLatitude();
}
then I am getting my location depending on these info:
Geocoder myLocation = new Geocoder(Time.this, Locale.getDefault());
List<Address> myList=null;
try {
myList = myLocation.getFromLocation(latitude,longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(myList != null && myList.size()>0) {
address= (Address) myList.get(0);
if(address.getAddressLine(0)!=null){
addressStr += address.getAddressLine(0);
}
if(address.getAddressLine(1)!=null){
addressStr += ", "+address.getAddressLine(1);
}
if(address.getAddressLine(2)!=null){
addressStr += ", " +address.getAddressLine(2);
}
}
But sometimes the location stays null until I restart my phone why that's happening? and is there a way to fix it?
Try to setup your Location Listener as below :
public class BasicMapActivity_new2 extends Activity implements
LocationListener {
private LocationManager locationManager;
private String provider;
Double Latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new2.this, "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if (!enabledWiFi) {
Toast.makeText(BasicMapActivity_new2.this,
"Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
// do something
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
// Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Latitude = lat;
longitude = lng;
Toast.makeText(BasicMapActivity_new2.this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#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
}
}
And do not forget to add permission into manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Update: This is because to add requestLocationUpdates() into onResume() and removeUpdates(this); into onPause(). This way your app will stop updated locations when it is not active. add below into your Activity:
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
this is a documented issue in google forums. Check this thread:
https://code.google.com/p/android/issues/detail?id=57707
Also i think the solution for this is to use Google Location API, this requires that you have Google Play services up to date and >= 2.2 i think. Hope this helps you. I battled this issue for long
Hello I have implemented a service that broadcasts the current location. the thing is the first time it updates it gives me 0.0 lat and 0.0 lon, which ruins the UI.how can I fix this?
Here is the code, thank you
public class LocationService extends Service {
protected LocationManager locationManager;
final static String MY_ACTION = "MY_ACTION";
MyLocListener myloc = new MyLocListener();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override public void onDestroy() {
};
#Override
public int onStartCommand(Intent intent, int flags, int startId){
final Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
LocationListener ll = new MyLocListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, ll);
Location location = new Location("abc");
ll.onLocationChanged(location);
Log.d("Last", ""+location.getLatitude());
return START_STICKY;
}
private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {
Log.d("1provider",location.toString());
Log.d("1Provider LOCATION CHANGED", location.getLatitude() + "");
Log.d("1Provider LOCATION CHANGED", location.getLongitude() + "");
Intent intent = new Intent();
intent.putExtra("location", location);
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Log.d("1Provider DIsabled", "Provider Disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("1Provider Enabled", "Provider Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("1Provider Changed", "Service Status Changed");
}
}
}
The onLocationChanged() method usually returns 0 on the first occasion - just check for this value and don't update the UI. As to it taking too long, it can take a while so run your service as an AsyncTask when getting the location, so that your UI thread is waiting around, and then update the UI when you get a return from the AsyncTask.
I want to keep my application running in background
I have an application that sends the user's location to our server
I have the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
updateWithNewLocation(null);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
public void updateWithNewLocation(Location location) {
if (location != null) {
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
long time = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
final String curTime = df.format(time);
final double lat = location.getLatitude();
final double lng = location.getLongitude();
final double alt = location.getAltitude();
System.out.println(lat);
System.out.println(lng);
System.out.println(alt);
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
/*Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('121.2149012','-6.217837','0.0','2012-05-07 10:20:01')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
I want my applicatioin to be running in the background. I want it to launch automatically when the phone is turned on
A very simple answer for your problem is to use Service. It will allow you to perform variety of tasks while being in background and is your best bet for sending your location to server silently.
Read this answer for help.
You can keep your application running in the background using Service
I hope this link will help you
Please read the documentation for further details
Run your background logic in a Service, and if you want to give a good UX experience (and to also have an higher priority) post a Notification to status-bar (using NotificationManager).
GrabLocationDetails.java
Use this code as your GrabLocationDetails.java
public class GrabLocationDetails extends Service implements LocationListener {
double lat,lng;
private LocationManager locationManager;
private String provider;
boolean isGps;
private ArrayList<String> mList;
Context GLDContext;
public GrabLocationDetails(Context cont){
this.GLDContext=cont;
}
public GrabLocationDetails(){}
#Override
public void onCreate() {
super.onCreate();
mList = new ArrayList<String>();
isGps = false;
lat=0.0;
lng=0.0;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//super.onStart(intent, startId);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
isGps = false;
ListAddItem(isGps);
SendBroadcast();
} else {
isGps = true;
Location location = locationManager.getLastKnownLocation(provider);
lat=(location.getLatitude());
lng=(location.getLongitude());
ListAddItem(true);
SendBroadcast();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} catch (Exception e) {
ListAddItem(isGps);
SendBroadcast();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
//locationManager.removeUpdates(this);
}
public void SendBroadcast(){
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(CommandExecutionModule.LocationDetails);
broadcastIntent.putExtra("Data", mList);
sendBroadcast(broadcastIntent);
}
public void ListAddItem(boolean GPS) {
//if(!GPS)
//mList.add("0");
//else
//mList.add("1");
mList.add(Double.toString(lat));
mList.add(Double.toString(lng));
}
/**************************************************************************************************************/
#Override
public void onLocationChanged(Location location){
locationManager.requestLocationUpdates(provider, 400, 1, this);
mList.clear();
lat = (location.getLatitude());
lng = (location.getLongitude());
ListAddItem(isGps);
SendBroadcast();
locationManager.removeUpdates(this);
stopSelf();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onProviderEnabled(String provider){
isGps=true;
}
#Override
public void onProviderDisabled(String provider){
isGps=false;
lat=0.0;
lng=0.0;
mList.clear();
ListAddItem(isGps);
//SendBroadcast();
}
You should use a Service and a BroadcastReceiver