how to timeout requestLocationUpdates? - android

When no GPS fix found, the code is getting stuck indefinitely in the looper.
I want to add a timeout so that if there is no GPS fix found, it should come out of the looper and execute the remaining part of the code.
I will really appreciate if you can help me in fixing this issue.
public class service_task extends Service {
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private class ServerThread extends Thread implements LocationListener {
public LocationManager locationManager = null;
public String msg = "default";
public String id = "default";
private Location mLocation = null;
public Socket socket = null;
public int serviceid;
public ServerThread(LocationManager locationManager, int startid) {
super("UploaderService-Uploader");
this.locationManager = locationManager;
this.serviceid=startid;
}
#SuppressLint("MissingPermission")
public void run() {
Looper.prepare();
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Looper.loop();
if (mLocation!=null) {
msg = "GPS data:" + mLocation;
}else{
msg ="No GPS data";
}
stopSelf(serviceid);
}
#Override
public void onLocationChanged(Location location) {
mLocation = location;
Log.d("D", String.valueOf(location));
this.locationManager.removeUpdates(this);
Looper.myLooper().quit();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("D", "startcommand");
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ServerThread thread = new ServerThread(locationManager,startId);
thread.start();
return START_REDELIVER_INTENT;
}
}

Create a Handler that uses your Looper: handler = new Handler(Looper.myLooper());
Then use handler.postDelayed(Runnable, long) to post a new Runnable that cancels location updates and quits your Looper after a given delay.

Related

how to send user location data to server every 5 second even app is closed?

How to send user location data to server every five second using restful API even app is closed in android?
Please help me
you can create a background service that it works when user lock screen or close your app from background
you must create service with this way:
first create a Service class like this:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks {
public static double latitude;
public static double longitude;
private int retryGPS = 0;
private int retryNetwork = 0;
private Handler handler;
private Runnable runnable;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
};
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1;
private static final String TAG = "LocationService";
#Override
public void onCreate() {
buildGoogleApiClient();
initializeLocationManager();
locationRequest();
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
sendLocation();
}
};
sendLocation();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private void locationRequest() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
}
private void sendLocation() {
//TODO: you can use location here
handler.postDelayed(runnable,5000);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
try {
Thread.sleep(3000);
onConnected(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
if (mLocationManager != null) {
for (LocationListener mLocationListener : mLocationListeners) {
try {
mLocationManager.removeUpdates(mLocationListener);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onDestroy();
}
private class LocationListener implements android.location.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
Location mLastLocation;
public LocationListener(String provider) {
Log.d(TAG, "LocationListener: " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(final Location location) {
mLastLocation.set(location);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d(TAG, "onLocationChanged: { latitude: " + latitude + " ,longitude: " + longitude + " , accuracy: " + location.getAccuracy() + " }");
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged: " + status);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
}
}
}
then register service in manifest:
<service
android:name=".service.LocationService"
android:enabled="true"
android:process=":process" />
then start service from any activity or fragment :
public static void mStopService(Context context) {
context.stopService(new Intent(context, LocationService.class));
}
public static void mStartService(Context context) {
context.startService(new Intent(context, LocationService.class));
}
if you want to make your code run even when the app is closed you need to use services, services can run in the background even if the app is closed, and you may need to use a broadcast receiver with the service to keep running it every time it finishes.
this is the Service:
public class myService extends Service {
public static int counter = 0;
public myReceiver myReceiver = new myReceiver();
#Override
public void onCreate() {
super.onCreate();
//this line register the Receiver for the first time
myService.this.registerReceiver(myReceiver, new IntentFilter("com.example.myApp"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Here you have to put the code that gets the location and send it
}
#Override
public void onDestroy() {
super.onDestroy();
//here you sent a broadcast message to start the reciever
//note that the broadcast message that you send has to be unique writing you package name will be fine ex: com.example.myApp
Intent sendBroadCast = new Intent("com.example.myApp");
sendBroadcast(sendBroadCast);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
and this is the broadcast receiver:
public class myReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if("com.example.myApp".equals(intent.getAction())){
//the handler is used as a timer here
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent myServ = new Intent(context, myService.class);
try {
context.startService(myServ);
}catch (Exception e){
}
}
},5000);
}
}
}

How to Restart a service after app is killed

I have to get location updates from location manager. I want the service remains continue if app is killed.
I have the following service class. I am using broadcast receiver. In onTaskRemove() method i send broadcast. in receiver class I restart the service, but not restarted. Please help. Thanks.
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
public GoogleService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
fn_getlocation();
}
#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 void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("ChangeStatus"));
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*rootIntent = new Intent("ChangeStatus");
rootIntent.putExtra("action", "statusChange");
sendBroadcast(rootIntent);*/
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("ChangeStatus"));
}
#SuppressLint("MissingPermission")
private void fn_getlocation(){
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable){
}else {
if (isNetworkEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
if (isGPSEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class TimerTaskToGetLocation extends TimerTask{
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
**my Reciver class is**
public class RestartServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), GoogleService.class));
}
}
my Manifest
<service android:name=".GoogleService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false"
></service>
<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="ChangeStatus" >
</action>
</intent-filter>
</receiver>
What i am doing wrong .
Use Pending Intent to get LocationUpdates using service upto android 7.0 above use you have to use Broadcast receiver:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if (result != null) {
List<Location> locations = result.getLocations();
Log.d("servicelocation","*******lastupdate "+result.getLastLocation());
Log.d("servicelocation","******* "+locations.size()+
"\n"+locations.get(locations.size()-1).getLatitude() +" " +
"lng "+locations.get(locations.size()-1).getLongitude());
Toast.makeText(getApplicationContext(),"Service Stared "+locations.size(),Toast.LENGTH_SHORT).show();
}
}
}else {
Log.d("serviceintentvalues","********");
}
return START_STICKY;
}
Here complete reference given be google samples : https://github.com/googlesamples/android-play-location
it's working well for me check...

Fragment BroadCast receiver not working

I'm making an app where I need to get constant location updates from a Service on a fragment, the problem is that the fragment is not getting the updates and I'm not sure what is the problem, here is the service:
public class GPService extends Service
{
private LocationManager locMan;
private Boolean locationChanged;
private Handler handler = new Handler();
static final int REQUEST_LOCATION = 1;
public static Location curLocation;
public static boolean isService = true;
public LocalBroadcastManager broadcast;
LocationListener gpsListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (curLocation == null) {
curLocation = location;
locationChanged = true;
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",curLocation.getLatitude());
intent.putExtra("latitud",curLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
locationChanged = false;
return;
}else
locationChanged = true;
curLocation = location;
if (locationChanged)
locMan.removeUpdates(gpsListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,Bundle extras) {
}
};
#Override
public void onCreate() {
super.onCreate();
curLocation = getBestLocation();
if (curLocation == null)
Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
else{
//Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
}
isService = true;
broadcast= LocalBroadcastManager.getInstance(this);
}
final String TAG="LocationService";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent i, int startId){
handler.postDelayed(GpsFinder,1);
}
#Override
public void onDestroy() {
handler.removeCallbacks(GpsFinder);
handler = null;
Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
isService = false;
}
public IBinder onBind(Intent arg0) {
return null;
}
public Runnable GpsFinder = new Runnable(){
public void run(){
Location tempLoc = getBestLocation();
if(tempLoc!=null)
curLocation = tempLoc;
tempLoc = null;
handler.postDelayed(GpsFinder,1000);
}
};
private Location getBestLocation() {
Location gpslocation = null;
Location networkLocation = null;
if(locMan==null){
locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
}
try {
if ( ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",gpslocation.getLatitude());
intent.putExtra("longitud",gpslocation.getLongitude());
Log.wtf("COORDENATES TO SEND",gpslocation.getLatitude()+" "+gpslocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
Log.wtf("LAS COORDENADAS a enviar SON",networkLocation.getLatitude()+" "+networkLocation.getLongitude());
intent.putExtra("latitud",networkLocation.getLatitude());
intent.putExtra("longitud",networkLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
}
The service is initiated in the activity like this
startService(new Intent(this, GPService.class));
In the fragment this is how I create it and register it
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
receiver= new GPSReceiver();
//this.getActivity().registerReceiver(receiver, new IntentFilter());
db=Database.getInstance(this.getContext());
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
getActivity().registerReceiver(receiver,filter);
}
#Override
public void onPause() {
getActivity().unregisterReceiver(receiver);
super.onPause();
}
Finally this is the reciever in the Fragment, I can't get it to get the info from the service, any ideas? I don't know what I'm doing wrong.
private class GPSReceiver extends BroadcastReceiver {
private LatLng changed;
public GPSReceiver()
{
changed= new LatLng(0,0);
}
#Override
public void onReceive(Context context, Intent intent) {
Log.wtf("RECIEVE", "IT IS IN BROADCAST");
if (intent.getAction().equals("GPSLocationUpdates"))
{
Log.wtf("RECIEVE1", "INTENT ARRIVES");
double lat= intent.getDoubleExtra("latitud",1);
double longi= intent.getDoubleExtra("longitud",1);
changed= new LatLng(lat,longi);
}
// String text = intent.getStringExtra("position");
}
public LatLng getChanged()
{
return changed;
}
}
The service seems to be working fine, I can see the coordinates in the console being send.
You're not registering you BroadcastReceiver to the LocalBroadcastManager. You're registering it to the global broadcast manager, but sending on the local.
Change:
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,filter);
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onPause();
}

Android: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I am making an android app where I am trying to get location using location manager and then I push that location to a server. When I try to do this I am getting the following error.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:223)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:223)
at android.location.LocationManager.wrapListener(LocationManager.java:851)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:864)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:459)
at com.pickingo.fe.services.gps.AppLocationService.getLocation(AppLocationService.java:30)
at com.pickingo.fe.gps.CurrentLocationPusher.run(CurrentLocationPusher.java:60)
at java.lang.Thread.run(Thread.java:818)
This is my appLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 50;
private static final long MIN_TIME_FOR_UPDATE = 1000*60*2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
This is the code I use to push the location after getting the location from the LocationManager.
public class CurrentLocationPusher implements Runnable {
private static CurrentLocationPusher _singleInstance;
private CurrentLocationPusher() {
this.apiClient = ApiClient.getInstance();
this.appLocationService = new AppLocationService(appContext);
this.runningThread = new Thread(this);
}
public static CurrentLocationPusher getInstance() {
if (_singleInstance == null)
synchronized (CurrentLocationPusher.class) {
if (_singleInstance == null)
_singleInstance = new CurrentLocationPusher();
}
return _singleInstance;
}
private boolean isStopThread = false;
public static final long ONE_MINUTE = 60 * 1000;
private static Context appContext;
private AppLocationService appLocationService;
private ApiClient apiClient;
private Thread runningThread;
public static void init(Context applicationContext) {
appContext = applicationContext;
}
#Override
public void run() {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
while (!isStopThread) {
try {
if (location != null)
if (CommonUtils.isActiveToInternet(appContext))
apiClient.getApi(appContext).pushLocation(String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()),String.valueOf(System.currentTimeMillis()),
String.valueOf(location.getAccuracy()));
Thread.sleep(ONE_MINUTE);
} catch (InterruptedException e) {
} catch (Exception e) {
Log.e(PickingoConstant.TAG, "error" + e.getMessage());
}
}
}
public void startPushingLocation() {
if (this.runningThread.getState() == Thread.State.NEW) {
runningThread.start();
isStopThread = false;
} else if (this.runningThread.getState() == Thread.State.TERMINATED) {
(runningThread = new Thread(this)).start();
isStopThread = false;
} else if (this.runningThread.getState() == Thread.State.RUNNABLE) {
return;
}
}
public void stopPushingLocation() {
isStopThread = true;
}
}
I am getting error at the following line in CurrentLocationPusher
.getLocation(LocationManager.GPS_PROVIDER);
If someone could give a hint or some assistance I would really appreciate it. Thanks in advance !!
As pointed out by Michael adding this code at starting of my run() method worked.
if (Looper.myLooper() == null) {
Looper.prepare();
}

Starting LocationManager as Service Android

What I'm attempting to do is when receiving a c2dm message, start a service that asks for location for 'x' amount of time and then hands that location off to our server. The c2dm message starts the service correctly, and the GPS location turns on, but it never updates. It just sits there for the length of time I specify (currently 12 seconds) in the thread and does nothing. I'm using the exact same code somewhere else in my app (not as a service) and it works perfectly. What am I doing wrong?
This starts the service when receiving a c2dm message.
context.startService(new Intent(context, ServicePingLocation.class));
This is the code for the service itself. All that ever gets called, is "onCreate" and "onStart".
public class ServicePingLocation extends Service implements LocationListener {
private final String DEBUG_TAG = "[GPS Ping]";
private boolean xmlSuccessful = false;
private boolean locationTimeExpired = false;
private LocationManager lm;
private double latitude;
private double longitude;
private double accuracy;
#Override
public void onLocationChanged(Location location) {
Log.d(DEBUG_TAG, "onLocationChanged");
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
}
#Override
public void onProviderDisabled(String provider) {
Log.d(DEBUG_TAG, "onProviderDisabled");
Toast.makeText(
getApplicationContext(),
"Attempted to ping your location, and GPS was disabled.",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Log.d(DEBUG_TAG, "onProviderEnabled");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10f, this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(DEBUG_TAG, "onStatusChanged");
}
#Override
public void onCreate() {
Log.d(DEBUG_TAG, "onCreate");
}
#Override
public void onDestroy() {
Log.d(DEBUG_TAG, "onDestroy");
}
#Override
public IBinder onBind(Intent intent) {
Log.d(DEBUG_TAG, "onBind");
return null;
}
#Override
public void onStart(Intent intent, int startid) {
Log.d(DEBUG_TAG, "onStart");
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10f, this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000,
300f, this);
Log.d(DEBUG_TAG, lm.toString());
new SubmitLocationTask(ServicePingLocation.this).execute();
}
private void locationTimer() {
new Handler().postDelayed(new Runnable() {
// #Override
#Override
public void run() {
locationTimeExpired = true;
}
}, 12000);
}
private class SubmitLocationTask extends AsyncTask<String, Void, Boolean> {
/** application context. */
private Context context;
private Service service;
public SubmitLocationTask(Service service) {
this.service = service;
context = service;
}
#Override
protected void onPreExecute() {
locationTimer(); // Start 12 second timer
}
#Override
protected void onPostExecute(final Boolean success) {
if (success && xmlSuccessful) {
lm.removeUpdates(ServicePingLocation.this);
onDestroy();
} else {
if (!GlobalsUtil.DEBUG_ERROR_MSG.equals(""))
Toast.makeText(getBaseContext(),
GlobalsUtil.DEBUG_ERROR_MSG, Toast.LENGTH_SHORT)
.show();
GlobalsUtil.DEBUG_ERROR_MSG = "";
}
}
#Override
protected Boolean doInBackground(final String... args) {
try {
DateFormat df = null;
df = new SimpleDateFormat("M/d/yy h:mm a");
Date todaysDate = new Date();// get current date time with
// Date()
String currentDateTime = df.format(todaysDate);
while ((accuracy > 100f || accuracy == 0.0)
&& !locationTimeExpired) {
// We just want it to sit here and wait.
}
return xmlSuccessful = SendToServerUtil.submitGPSPing(
0, longitude,
latitude, accuracy, currentDateTime);
} catch (Exception e) {
return false;
}
}
}
}
[Edit]
Fixed the issue I was having. Code was actually working. I added the network provider, adjusted the onDestroy() method to stop the service, and tweaked the time used to grab GPS signal.
Thank you for the advice, CommonsWare
Fixed the issue I was having. Code was actually working. I added the network provider, adjusted the onDestroy() method to stop the service, and tweaked the time used to grab GPS signal.
Thank you for the advice, CommonsWare

Categories

Resources