Why location service stopped to send location updates when i locked phone - android

I have created background service to get user location periodically and send it to server like this :`
public class SyncDataToServerService extends Service {
private static final String TAG = "SyncDataToServerService";
private ServerCall serverCall;
private SharedPreferences tempPref2;
private Timer timer;
LocationManager locationManager;
UtilityClass utilityClass;
PowerManager.WakeLock wakeLock;
PowerManager powerManager;
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
serverCall = new ServerCall(this);
timer = new Timer();
utilityClass = new UtilityClass(this);
tempPref2 = getSharedPreferences(getString(R.string.temp_pref_name_2), Context.MODE_PRIVATE);
}
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e(TAG, "onStartCommand");
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager != null)
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyApp::MyWakelockTag");
wakeLock.acquire();
//initialize and start Location service
startLocation();
//initialize and start the TimerTask's job
startTimer();
return START_STICKY;
}
#SuppressLint("MissingPermission")
private void startLocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager != null)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
10, new MyLocationListener());
if (locationManager != null)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
10, new MyLocationListener());
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
if (locationManager != null)
locationManager.removeUpdates(new MyLocationListener());
super.onDestroy();
}
private void syncPath(Location mLocation) {
Log.w(TAG, "Location: " + mLocation + " Latitude: " + mLocation.getLatitude() + " & Longitude: "
+ mLocation.getLongitude());
if (tempPref2.getString(getString(R.string.attendance_key), "").equalsIgnoreCase("present")) {
serverCall.sendEmpPath(mLocation);
}
}
private void startTimer() {
TimerTask timerTask = new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void run() {
if (utilityClass.isInternetConnected()) {
if (serverCall != null) {
if (serverCall.requestQ.size() > 0)
Log.e(TAG, "Request queue size ==" + serverCall.requestQ.size());
serverCall.syncData();
}
}
}
};
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000);
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
Intent intent1 = new Intent("com.example.mc_project");
intent1.putExtra("location", location);
sendBroadcast(intent1);
if (location.getAccuracy() < 25)
syncPath(location);
wakeLock.release();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}`
everything working fine but when i lock my phone it stop to send location updates. i have read that it is because of system sleep and have to use wake lock but it also not working.And when i unlock phone it suppose to start to send location updates but this also not happening.My service do not stop,it always in running state.Please help where i am doing wrong or missing something.

you should use foreground service and put location update code inside it .
os stops background service any time power is off

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

Check location in Alarm Manager

I need to check current user location every 10 minutes even if user turned off the screen or closed app (not Force stop). For start of LocationCheckService I'm using AlarmService, but it's start to checking location always (onLocationChanged, for example). How to make only one request for location update every 10 minutes (without onLocationChanged every time) via Network or GPS provider?
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, LocationCheckService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 100, 200, pendingIntent);
}
}
LocationCheckService.class
public class LocationCheckService extends Service {
LocationManager locationManager = null;
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, new LocationListener(LocationManager.NETWORK_PROVIDER));
new Timer().schedule(new MyTimer(), 0, 10000);
}
#SuppressLint("MissingPermission")
class MyTimer extends TimerTask {
#SuppressLint("MissingPermission")
#Override
public void run() {
try {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> listAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddress != null && listAddress.size() > 0)
Log.d(TAG, listAddress.get(0).getCountryCode());
listAddress = geocoder.getFromLocation(1.3707295, 32.3032414, 1);
if (listAddress != null && listAddress.size() > 0)
Log.d(TAG, listAddress.get(0).getCountryCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
}

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...

Use less battery with GPS location every 15 minutes

I'm implementing an application which need to send a location to GCM every 15 minutes. I implemented an AlarmManager which will be called every 15 minute.
Here is my class of my alarmmanager
public class LocationAlarmManager {
Context mContext = null;
public LocationAlarmManager (Context context) {
mContext = context;
}
private AlarmManager alarmManager;
private Intent gpsTrackerIntent;
private PendingIntent pendingIntent;
private static final String TAG = "LocationAlarmManager";
public void startAlarmManager() {
Log.d(TAG, "startAlarmManager");
alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
gpsTrackerIntent = new Intent(mContext, GpsTrackerAlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(mContext, 0, gpsTrackerIntent, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
15 * 60000, // 60000 = 1 minute
pendingIntent);
}
public void cancelAlarmManager() {
Log.d(TAG, "cancelAlarmManager");
Intent gpsTrackerIntent = new Intent(mContext, GpsTrackerAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, gpsTrackerIntent, 0);
AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
That one calls GpsTrackerAlarmReceiver
// make sure we use a WakefulBroadcastReceiver so that we acquire a partial wakelock
public class GpsTrackerAlarmReceiver extends WakefulBroadcastReceiver {
private static final String TAG = "GpsTrackerAlarmReceiver";
#Override
public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, SmartLocationService.class));
}
}
For handling my location I implemented the following in my SmartLocationService.
public class SmartLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "SmartLocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private LocationClient locationClient;
public LocationManager locationManager;
Context context;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public Location previousBestLocation;
private double mLastLatitudeLocation = 0;
private double mLastLongitudeLocation = 0;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(this,this,this);
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location loc) {
MessageHandler messageHandler = new MessageHandler(SmartLocationService.this);
messageHandler.sendLocationMessage(loc); //send location to GCM
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
sendLocationDataToWebsite(location);
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
context = getApplicationContext();
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(900000); // milliseconds
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient.requestLocationUpdates(locationRequest, this);
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected");
stopLocationUpdates();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
}
This works, but my locationservice get called more then once in my timeslot of 15 minutes. Anyone know why? Is this a good way to use less battery power (GPS)?
Thanks

Android: Alarm fired up before actual alarm time

My app is a tracker app, that uses GPS. At every 15 minutes, it finds current location of user. For this, I had used AlarmManager. I am getting The current location through a background service, which is scheduled to run at every 15 minutes. This service will be started by the broadcast receiver upon alarm. But, the problem is alarm fires up before time, i.e. once service started and finished its work, service was supposed to be called after 15 minutes. But, it is getting called at interval of 2-3 minutes.
Activity code
AlarmManager AlmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Sender = PendingIntent.getBroadcast(GpsTrackActivity.this, 0,
AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlmMgr.setRepeating(AlarmManager.RTC_WAKEUP, 0, 15 * 60 * 1000,
Sender);
BroadcastReceiver
public class StartServiceReceiver extends BroadcastReceiver
{
private static final String TAG = "StartServiceReceiver";
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context, MyLocationService.class);
context.startService(serviceIntent);
Log.v(TAG, "onReceive called");
}
}
Service Class
public class MyLocationService extends Service implements
OnLocationReceivedListener {
private LocationManager manager;
private Location location = null;
PowerManager powerManager;
private WakeLock wakeLock;
private String city, time, udid;
private String country;
GPSLocationListener mGPSLocationListener;
NetworkLocationListener mNetworkLocationListener;
private static final int MAX_ATTEMPTS = 250;
private static String TAG = "MyLocationService";
LocTimerTask mTimerTask;
int mSattelites;
Timer myLocTimer;
int i = 0;
boolean isGPS;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand called");
getCurrentLocation();
time = getCurrentTime();
udid = getDeviceId();
return 1;
}
#Override
public void onCreate() {
Log.v(TAG, "onCreate called");
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"mywakelock");
mGPSLocationListener = new GPSLocationListener();
mNetworkLocationListener = new NetworkLocationListener();
wakeLock.acquire();
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public String getCurrentTime() {
String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.getDefault()).format(new Date());
return currentTime;
}
public String getDeviceId() {
TelephonyManager tm = (TelephonyManager) MyLocationService.this
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
public void getCurrentLocation() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.addGpsStatusListener(mGPSStatusListener);
mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L,
50.0f, mGPSLocationListener);
} else {
turnGPSOn();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L,
50.0f, mGPSLocationListener);
}
myLocTimer = new Timer("LocationRunner", true);
myLocTimer.schedule(mTimerTask, 0, 1000);
}
public String getLong(Location loc) {
String longi = null;
if (loc != null) {
longi = Double.toString(loc.getLongitude());
}
return longi;
}
public String getLat(Location loc) {
String lat = null;
if (loc != null) {
lat = Double.toString(loc.getLatitude());
}
return lat;
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location argLocation) {
location = argLocation;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class LocTimerTask extends TimerTask {
String provider;
public LocTimerTask(String provider) {
this.provider = provider;
}
final Handler mHandler = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
#Override
public void run() {
i++;
Log.v(TAG, "Timer Task run " + i);
location = manager.getLastKnownLocation(provider);
if (location != null) {
Log.v(TAG, "in timer task run in if location not null");
isGPS = true;
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
} else {
Log.v(TAG, "in timer task run in else location null");
isGPS = false;
if (location == null && i == MAX_ATTEMPTS) {
Log.v(TAG, "if 1 max attempts done");
turnGPSOff();
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.v(TAG,
"if 1 max attempts done Location from network not null");
Log.v(TAG,
"if 1 max attempts done Location from network not null coordinates not null");
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
i = 0;
return;
} else {
i = 0;
return;
}
} else {
return;
}
}
}
};
public void run() {
mHandler.post(r);
}
}
private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {
#Override
public synchronized void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.v(TAG, "GPS SAtellitestatus");
GpsStatus status = manager.getGpsStatus(null);
mSattelites = 0;
Iterable<GpsSatellite> list = status.getSatellites();
for (GpsSatellite satellite : list) {
if (satellite.usedInFix()) {
mSattelites++;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(getApplicationContext(), "Got First Fix",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STARTED:
Toast.makeText(getApplicationContext(), "GPS Event Started",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
Toast.makeText(getApplicationContext(), "GPS Event Stopped",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
};
public void onDestroy() {
super.onDestroy();
if (myLocTimer != null) {
myLocTimer.cancel();
myLocTimer.purge();
}
if (mTimerTask != null) {
if (mTimerTask.r != null) {
mTimerTask.mHandler.removeCallbacks(mTimerTask.r);
}
}
if (manager != null) {
if (mGPSLocationListener != null) {
manager.removeUpdates(mGPSLocationListener);
}
if (mNetworkLocationListener != null) {
manager.removeUpdates(mNetworkLocationListener);
}
if (mGPSStatusListener != null) {
manager.removeGpsStatusListener(mGPSStatusListener);
}
}
Toast.makeText(getApplicationContext(), "Service onDestroy called",
Toast.LENGTH_LONG).show();
}
#Override
public void onLocationReceived(Location mLoc) {
String lat = getLat(mLoc);
String lon = getLong(mLoc);
if (NetworkConnection.isOnline(getApplicationContext())) {
new SendDataAsynctask(lat, lon, "", time, udid, city, country,
wakeLock).execute();
Log.v(TAG, "net available");
} else {
Toast.makeText(getApplicationContext(), "Network unavailable",
Toast.LENGTH_LONG).show();
Log.v(TAG, "net unavailable");
}
}
}
I have a doubt, does AlarmManager gets affected by Timer or TimerTask. I am asking this because within my service I had used Timer, since it takes time for GPS to find first fix.

Categories

Resources