package com.ved.musicmapapp.services;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.R.bool;
import android.app.Service;
import android.app.ActionBar.Tab;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.ved.musicmapapp.MainActivity;
//import com.ved.musicmapapp.providers.SyncSongTask;
import com.ved.musicmapapp.providers.UpdateLocationTask;
import com.ved.musicmapapp.utils.SettingsManager;
import com.ved.musicmapapp.utils.Statics;
import com.ved.musicmapapp.utils.Utils;
public class UpdateLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
public static final int SYNCING_FREQUENCY = 30 * 60 * 1000; // 30 mins
public static final int UPDATE_DURATION = 10000; // 5 second
public static final int UPDATE_SEQUENT = 60 * 60 * 1000;// 1 hour
public static final double MIN_DISTANCE = 500.0;// meter
public static boolean isServiceSyncing = false;
private final IBinder mBinder = new ServiceBinder();
UpdateLocationTask mUpdateLocationTask = null;
private Timer mTimer, syncingTimer, mTimerCheckLocation;
public static long lastSync = 0;
private Handler mHandler;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// private SyncSongTask syncTask;
private SharedPreferences prefs, mSharedPreferences;
private Editor edt;
private CountDownTimer mCDT;
public static boolean isGetData;
private BroadcastReceiver networdReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()
&& SettingsManager.getInstance(context)
.isAutoUpdateLocation()) {
Pair<Double, Double> lastLocation = getLastLocation(context);
if (!prefs.getBoolean("location_committed", false)
&& lastLocation != null) {
if (mUpdateLocationTask != null) {
mUpdateLocationTask.cancel(true);
mUpdateLocationTask = null;
}
commit(lastLocation.first, lastLocation.second);
}
// Log.e("check","Calling start syncing From Update Location Service,,,");
// startSyncing();
Log.i("SyncSongTask", "on network");
}
}
};
BroadcastReceiver synSongBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("check","Calling start syncing From Broadcast receiver,,,");
// startSyncing();
Log.i("SyncSongTask", "on song");
}
};
public void startSyncing() {
Log.e("check","IN start syncing,,,");
if (isServiceSyncing) {
return;
}
// syncTask = new SyncSongTask(UpdateLocationService.this) {
//
// @Override
// protected void onPreExecute() {
// isServiceSyncing = true;
// super.onPreExecute();
// Log.i("SyncSongTask", "in Update Location Service");
// }
//
// @Override
// protected void onPostExecute(Boolean result) {
// super.onPostExecute(result);
// isServiceSyncing = false;
// lastSync = System.currentTimeMillis();
// }
//
// @Override
// protected void onCancelled(Boolean result) {
// // TODO Auto-generated method stub
// super.onCancelled(result);
// Log.i("SyncSongTask", "cancelled");
// isServiceSyncing = false;
// }
// };
// syncTask.execute();
}
public static Pair<Double, Double> getLastLocation(Context context) {
SharedPreferences prefs = context.getSharedPreferences("MUSIC_MAP",
Context.MODE_PRIVATE);
Pair<Double, Double> lastLocation = null;
if (prefs.contains("LAST_LONGITUDE") && prefs.contains("LAST_LATITUDE")) {
lastLocation = new Pair<Double, Double>(Double.parseDouble(prefs
.getString("LAST_LATITUDE", "0")), Double.parseDouble(prefs
.getString("LAST_LONGITUDE", "0")));
}
return lastLocation;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class ServiceBinder extends Binder {
UpdateLocationService getService() {
return UpdateLocationService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
registerReceiver(networdReceiver, new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(synSongBroadcastReceiver, new IntentFilter(
"com.ved.musicmapapp.service.syncsong"));
mTimer = new Timer();
mTimerCheckLocation = new Timer();
syncingTimer = new Timer();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
if (SettingsManager.getInstance(getApplicationContext())
.isAutoUpdateLocation()) {
if (!mLocationClient.isConnected()) {
startLocationUpdate();
}
}
}
super.handleMessage(msg);
}
};
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_DURATION);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(UPDATE_DURATION / 5);
prefs = getSharedPreferences("MUSIC_MAP", Context.MODE_PRIVATE);
mSharedPreferences = getSharedPreferences("settings",
Context.MODE_PRIVATE);
edt = prefs.edit();
// isGetData = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mCDT = new CountDownTimer(10 * 1000, 10 * 1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
if (mLocationClient.isConnected()) {
checkLocation(null);
mLocationClient.disconnect();
}
}
};
mTimerCheckLocation.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
startLocationUpdate();
mCDT.start();
}
}, 0, mSharedPreferences.getLong("auto_update_location_schedule",
30 * 60 * 1000));
if (mTimer != null) {
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.sendEmptyMessage(1);
}
}, 0, SettingsManager.getInstance(getApplicationContext())
.getAutoLocationSchedule());
}
// Toast.makeText(getBaseContext(), "Start Sync",
// Toast.LENGTH_SHORT).show();
/*syncingTimer.schedule(new TimerTask() {
@Override
public void run() {
// if (isServiceSyncing || MainActivity.isMainSyncing) {
if (isServiceSyncing) {
lastSync = System.currentTimeMillis();
}
Log.e("check","Calling start syncing From Scheduler,,,");
startSyncing();
Log.i("SyncSongTask", "on timer");
}
}, 0, SYNCING_FREQUENCY);*/
return START_NOT_STICKY;
}
public void checkLocation(Location location) {
double distance = 0;
if (location == null) {
if(mLocationClient != null)
location = mLocationClient.getLastLocation();
}
Pair<Double, Double> lastLocation = getLastLocation(this.getApplicationContext());
if (lastLocation == null && location != null) {
} else {
if (location != null && lastLocation != null) {
distance = Utils.distance(lastLocation.first,
lastLocation.second, location.getLatitude(),
location.getLongitude()) * 1000;
} else {
return;
}
if (distance < MIN_DISTANCE) {
return;
}
}
if (Statics.isNetworkConnected(getApplicationContext())) {
commit(location.getLatitude(), location.getLongitude());
}
}
public void startLocationUpdate() {
// try{
if (mLocationClient != null && mLocationClient.isConnected()) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} else {
try {
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_DURATION);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(UPDATE_DURATION / 5);
// mLocationClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
// }
// catch(Exception e){
// e.printStackTrace();
// }
}
@Override
public void onDestroy() {
// locationManager.removeUpdates(this);
unregisterReceiver(networdReceiver);
unregisterReceiver(synSongBroadcastReceiver);
mTimer.cancel();
mTimer.purge();
syncingTimer.cancel();
syncingTimer.purge();
mLocationClient.disconnect();
if (mUpdateLocationTask != null) {
mUpdateLocationTask.cancel(true);
}
super.onDestroy();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private void commit(final double latitdue, final double longitude) {
mUpdateLocationTask = new UpdateLocationTask(getApplicationContext(),
latitdue, longitude,
new UpdateLocationTask.UpdateLocationListener() {
@Override
public void onUpdateComplete(boolean isSuccess) {
edt = prefs.edit();
edt.putString("LAST_LONGITUDE",
String.valueOf(longitude));
edt.putString("LAST_LATITUDE", String.valueOf(latitdue));
edt.commit();
}
});
mUpdateLocationTask.execute();
}
@Override
public void onLocationChanged(Location location) {
mCDT.cancel();
checkLocation(location);
if (mLocationClient.isConnected()) {
mLocationClient.disconnect();
}
}
}