I am having Service using which we are getting the GPS Location by using callback method onLocation. And Android Service gets called every 3 seconds. Now I want to run the Service even if the App is cleared or killed from background.
In onStartCommand we are returning START_STICKY but the service onStartCommand is not getting called after clearing / killing of app.
public class GPSBackgroundService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final String POLL_FREQUENCY = "frequency";
public static final String INITIATED_BY = "initiatedBy";
public static final String INITIATED_SCREEN = "initiated_screen";
ServiceComponent serviceComponent;
//public LocationManager locationManager;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
static Location previousPosition = null;
double preLatitude, preLongitude;
boolean haveLocationPermissionAccess = false, trackStoredLocally = false;
String presentLat = "", presentLon = "";
float totalDistTravelled = 0f;
String dist_travelled = "0", previousDist = "", currentDate = "";
int pollFrequency = 10000;
String speed_calculated = "0.0";
PreferencesHelper mPreferenceHelper;
long preLongTime = 0L;
//handler to update bunch of points in interval seq.
Handler bulkLatLngThroughputManager;
Runnable bulkLatLngThroughputEmployee;
SimpleDateFormat mdformat;
int notificationId = 5173;
NotificationManager notificationManager = null;
/*NotificationManagerCompat notificationManager = null;*/
Notification notification = null;
NotificationCompat.Builder notificationBuilder = null;
String dist = "0.0", text = "";
int count = 0, countForTrackPoints = 0;
static Location currentLocation;
boolean allowForAnotherTrackCall= true;// =true for allowance and =false for dis allowance
int success = 0,fail = 0,init = 0,dbs = 0,dbf = 0, rls=0;
Intent requirementsOfListFragment,requirementsOfMapFragment;
String initiatedBy = "";
static String initiatedScreen = "";
String channelId = "",channelName = "";
Double dist_temp = 0d;
public static boolean allowNetworkCall = true;
#Override
public void onCreate() {
super.onCreate();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onCreate called=" + totalDistTravelled, "abc.txt");
ConfigPersistentComponent configPersistentComponent = DaggerConfigPersistentComponent.builder()
.applicationComponent(SuprabhatApplication.get(getApplicationContext()).getComponent())
.build();
serviceComponent = configPersistentComponent.serviceComponent(new ServiceModule(this));
serviceComponent.inject(this);
mPresenter.attachView(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStartCOMMAND called=" + totalDistTravelled, "abc.txt");
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
notificationBuilder = new NotificationCompat.Builder(this);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MAX)
.setContentText("Live tracking in progress...!")
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setChannelId(channelId)
.build();
notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(notificationId, notification);
}
notificationManager.notify(notificationId, notification);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStartCOMMAND Leaving=" + totalDistTravelled, "abc.txt");
return START_STICKY;
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager) {
channelId = "my_service_channelid";
channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_LOW);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
#Override
public void onStart(Intent intent, int startId) {
Log.i("onStart","onStart called");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart called=" + totalDistTravelled, "abc.txt");
pollFrequency = intent.getIntExtra(POLL_FREQUENCY, pollFrequency);
initiatedBy = intent.getStringExtra(INITIATED_BY);
initiatedScreen = intent.getStringExtra(INITIATED_SCREEN);
countForTrackPoints = mPresenter.getTrackLastCount();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart FieldStaffTrans Count="+String.valueOf(countForTrackPoints), "abc.txt");
// Create the Foreground Service
currentDate = CommonUtils.getCurrentDate();
bulkLatLngThroughputManager = new Handler();
bulkLatLngThroughputEmployee = new Runnable() {
#Override
public void run() {
sendTrackedPointsToRemoteLoc(initiatedScreen);
allowForAnotherTrackCall = false;
bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee, pollFrequency);
}
};
mdformat = new SimpleDateFormat("HH:mm:ss");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// stopSelf();
return;
}
haveLocationPermissionAccess = true;
if (mPresenter != null) {
totalDistTravelled = mPresenter.getTrackDistanceTravelled();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart Started SHREDPREF totalDistTravelled="+String.valueOf(countForTrackPoints),"abcDistance.txt");
dist_travelled = mPresenter.getTrackDistanceCalculated();
}
buildGoogleApiClient();
/*locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);*/
bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee, pollFrequency);
requirementsOfListFragment = new Intent(CustomersInListFragment.GET_UPDATED_LOCATION_INFO);
requirementsOfMapFragment = new Intent(CustomersOnMapFragment.GET_UPDATED_LOCATION_INFO);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart after buildGoogleApiClient called=" + totalDistTravelled, "abc.txt");
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(3000);
mLocationRequest.setFastestInterval(3000 / 2);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient.connect();
}
public void sendTrackedPointsToRemoteLoc(String initiatedScreenLocal) {
//Toast.makeText(SuprabhatApplication.getInstance(), "sendTrackedPointsToRemoteLoc called " + CommonUtils.getCurrentDateInYYYYMMDDFormat(), Toast.LENGTH_SHORT).show();
initiatedScreen = initiatedScreenLocal;
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPointsToRemoteLoc called InitiatedScr=" + initiatedScreenLocal + " totalDistTravelled=" + totalDistTravelled, "abc.txt");
if (allowNetworkCall) {
ArrayList<LatLngHolder> latLngHolderArrayList = new ArrayList<>();
ArrayList<LatLngHolder> trackedPoints = mPresenter.getAllFSRTrackedRecords(currentDate);
if (trackedPoints.size() > 0) {
trackStoredLocally = true;
latLngHolderArrayList.addAll(trackedPoints);
rls = trackedPoints.size();
}
if (presentLat != null && presentLon != null && !presentLat.isEmpty() && !presentLon.isEmpty()) {
if(countForTrackPoints > mPresenter.getTrackLastCount())
countForTrackPoints += 1;
else {
countForTrackPoints = mPresenter.getTrackLastCount();
countForTrackPoints += 1;
}
//dist_temp += 100;
LatLngHolder holder = new LatLngHolder(presentLat, presentLon, dist_travelled, speed_calculated, "", String.valueOf(countForTrackPoints), "Live");
//LatLngHolder holder = new LatLngHolder(presentLat, presentLon, String.valueOf(dist_temp), speed_calculated, "", String.valueOf(countForTrackPoints), "Live");
latLngHolderArrayList.add(holder);
if (latLngHolderArrayList.size() > 1) {
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
} else if (latLngHolderArrayList.size() > 0) {
String strServerSentLattitude = mPresenter.getServerSentLattitude();
String strServerSentLongitude = mPresenter.getServerSentLongitude();
Double serverSentLatt,serverSentLong;
if (strServerSentLattitude ==null || strServerSentLongitude == null) {
serverSentLatt = currentLocation.getLatitude();
serverSentLong = currentLocation.getLongitude();
mPresenter.setServerSentLattitude(String.valueOf(serverSentLatt));
mPresenter.setServerSentLongitude(String.valueOf(serverSentLong));
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
} else {
serverSentLatt = Double.parseDouble(mPresenter.getServerSentLattitude());
serverSentLong = Double.parseDouble(mPresenter.getServerSentLongitude());
float[] results = new float[1];
Location.distanceBetween(
serverSentLatt, serverSentLong,
currentLocation.getLatitude(), currentLocation.getLongitude(), results);
float difference = results[0];
/* mPresenter.sendTrackedPoints(latLngHolderArrayList,initiatedBy);
/* mPresenter.sendTrackedPoints(latLngHolderArrayList,initiatedBy);
previousLocation = currentLocation;*/
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints serverSentLatt="+serverSentLatt, "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints serverSentLong="+serverSentLong, "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints currentPosition.getLatitude()="+currentLocation.getLatitude(), "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints currentPosition.getLongitude()="+currentLocation.getLongitude(), "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints calulated distanceDiff=" + difference, "abc.txt");
if (difference >= 40) {//40
mPresenter.setServerSentLattitude(String.valueOf(currentLocation.getLatitude()));
mPresenter.setServerSentLongitude(String.valueOf(currentLocation.getLongitude()));
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " InitiatingToHitServer>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + difference, "abc.txt");
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
//preLatitude = currentLocation.getLatitude();
//preLongitude = currentLocation.getLongitude();
} else {
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPointsToRemoteLoc distanceLesssThen40=" + initiatedScreenLocal + " totalDistTravelled=" + totalDistTravelled, "abc.txt");
countForTrackPoints -= 1;
}
//mPresenter.sendTrackedPoints(latLngHolderArrayList);
}
}
/*++init;
notificationBuilder.setContentText("i: " + init + " s: " + success + " f: " + fail + " dbs: " + dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId, notificationBuilder.build());*/
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
// n/w calls status illuminators
#Override
public void onSendingBulkTrackedPoints(FieldStaffPositionBackgroundPresenter.FieldNotesStartOrStopResultsCarrier resultsCarrier) {
int tempTrackedPointsStrd = mPresenter.getTrackLastCount();
if (tempTrackedPointsStrd < countForTrackPoints)
mPresenter.storeTrackCurrentCount(countForTrackPoints);
count++;
if (trackStoredLocally) {
//clear all local storage tracks
mPresenter.deleteAllFsrStoredTracks();
trackStoredLocally = false;
}
if (resultsCarrier.getStopLiveTracking().equalsIgnoreCase("Y")) {
mPresenter.storeTrackDistanceCalculated("0");
mPresenter.storeTrackDistanceTravelled(0f);
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
// this.stopSelf();
} else {
}
allowForAnotherTrackCall = true;
/*++success;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onTrackPointsSendingError(String exception) {
mPresenter.storeTrackCurrentCount(countForTrackPoints);
mPresenter.storeFailedTrackInLocal(presentLat, presentLon, dist_travelled, speed_calculated, currentDate, mdformat.format(new Time(System.currentTimeMillis())), String.valueOf(countForTrackPoints));
//bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee,pollFrequency);
allowForAnotherTrackCall = true;
//FieldStaffPositionBackgroundTransmitter.writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onTrackPointsSendingError " + exception,"respnse.txt");
/*++fail;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onTrackPointsSendingFailure(int statusCode, String message) {
mPresenter.storeTrackCurrentCount(countForTrackPoints);
mPresenter.storeFailedTrackInLocal(presentLat, presentLon, dist_travelled, speed_calculated, currentDate, mdformat.format(new Time(System.currentTimeMillis())), String.valueOf(countForTrackPoints));
//bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee,pollFrequency);
allowForAnotherTrackCall = true;
/*++fail;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
//FieldStaffPositionBackgroundTransmitter.writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onTrackPointsSendingFailure " + message,"respnse.txt");
}
#Override
public void onLocalStorageOfTrackSuccess() {
/*++dbs;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onLocalStorageOfTrackFailed(String exception) {
/*++dbf;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
public void writeDataToFile(String highestScore, String fileName) {
try {
// if (mPresenter.getFFAEnableLogging().equals("Y")) {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, fileName);
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
bw.write(String.valueOf(highestScore));
//bw.append(String.valueOf(highestScore));
bw.close();
// }
} catch (IOException e) {
e.printStackTrace();
}
}
//location related predefined helpers
#Override
public void onLocationChanged(Location location) {
if (location != null ) {
currentLocation = location;
requirementsOfListFragment.putExtra(CustomersInListFragment.PLOFS, presentLon);
requirementsOfListFragment.putExtra(CustomersInListFragment.DCFS, dist_travelled);
requirementsOfListFragment.putExtra(CustomersInListFragment.SCFS, speed_calculated);
requirementsOfListFragment.putExtra(CustomersInListFragment.TDTFS,totalDistTravelled);
LocalBroadcastManager.getInstance(this).sendBroadcast(requirementsOfListFragment);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLAFS, presentLat);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLOFS, presentLon);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.DCFS, dist_travelled);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.SCFS, speed_calculated);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLADFS,lat);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLODFS,lon);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.TDTFS,totalDistTravelled);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.CLBR,location.getBearing());
LocalBroadcastManager.getInstance(this).sendBroadcast(requirementsOfMapFragment);
//++dbs;
//notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs);
//notificationManager.notify(notificationId,notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
/*#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
*//*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);*//*
}*/
public void adamantForceCloseOfService()
{
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
/*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*/
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
// stopSelf();
}
#Override
public void onDestroy() {
/* writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onDestroyCalled", "abc.txt");
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
*//*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*//*
if (notificationManager != null) {
notificationManager.cancel(notificationId);
notificationManager.cancelAll();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(channelId);
}
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
stopSelf();
super.onDestroy();*/
//stopSelf();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onDestroyCalled", "abc.txt");
Log.i("onDestroy","onDestroy Called");
Intent broadcastIntent = new Intent(this, FieldStaffRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onTaskRemoved called", "abc.txt");
Log.i("EXIT", "onTaskRemoved!");
Intent broadcastIntent = new Intent(this, FieldStaffRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
//stoptimertask();
}
/* #Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
*//*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*//*
if (notificationManager != null) {
notificationManager.cancel(notificationId);
notificationManager.cancelAll();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(channelId);
}
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
stopSelf();
*//*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}*//*
}*/
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
I am testing in real Mobile device and I have tested in multiple devices mentioned below but in none the service onStartCommand was invoked after app was cleared from background.
Lenovo k7 power Android 7.0
Xiaomi Redmi 8A Dual Android 10 ( here i enabled Auto Start from setting privacy )
Moto G6 ( Android 9.0 )
Note : For Reference i have posted the service code that we are using. pls let me know why onStartCommand is not getting called after app was cleared from background.
Related
I want to track the user location. So I have made a code so that on every 10 mins of interval its location should be hit on server. If it is not moving also the location should hit at 10 min of interval. I set Location interval minutes for 10 min public static final long LOCATION_INTERVAL_MINUTES = 10 * 60 * 1000;
It should update the location with 10 min, but it hits randomly. I also increase the gps frequency distance from 10 to gpsFreqInDistance = 100 .Random hits are stopped but it will not updated on 10 mins of interval.
So what to do to get location at 10 min of interval.
Below is my manifiest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
As for Android above 10version u cant use background location and foreground location simultaneously. So i comment the ACCESS_BACKGROUND_LOCATION" in my project.
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private Context mContext;
private LocationRepository mLocationRepository;
private ShareLocationAdapterClass mAdapter;
private SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private List<UserLocationPojo> mUserLocationPojoList;
private SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
public LocationMonitoringService(final Context context) {
mContext = context;
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
int gpsFreqInDistance = 100;
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking() {
mAdapter.shareLocation();
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
if (AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext))
userLocationPojo.setIsOffline(true);
else
userLocationPojo.setIsOffline(false);
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Below is the foreground service which i have used
public class ForgroundService extends Service {
private LocationMonitoringService monitoringService;
private Handler locationHandler;
private Runnable locationThread;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
monitoringService = new LocationMonitoringService(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
Log.d("okh", "onStartCommand: ");
final int currentId = startId;
locationThread = new Runnable() {
public void run() {
monitoringService.onStartTacking();
}
};
locationHandler = new Handler(Looper.getMainLooper());
locationHandler.post(locationThread);
startLocationForeground();
return Service.START_STICKY;
// return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
locationHandler.removeCallbacks(locationThread);
monitoringService.onStopTracking();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
stopForeground(STOP_FOREGROUND_REMOVE);
}
if(Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY,false))
{
Intent broadcastIntent = new Intent(this, RestarterBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
}
}
private void startLocationForeground() {
if (Build.VERSION.SDK_INT >= 26) {
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? this.createNotificationChannel("my_service", "My Background Service")
: "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder((Context) this,
channelId);
Notification notification = notificationBuilder
.setOngoing(true)
.setContentText("Please don't kill the app from background. Thank you!!")
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setPriority(-2)
.setCategory("service")
.build();
startForeground(101, notification);
}
}
#RequiresApi(26)
private String createNotificationChannel(String channelId, String channelName) {
NotificationChannel chan = new NotificationChannel(channelId, (CharSequence)channelName,
NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(chan);
return channelId;
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int color = 0x008000;
notificationBuilder.setColor(color);
return R.drawable.ic_noti_icon;
}
return R.drawable.ic_noti_icon;
}
}
Why you are passing null in the last parameter? Did you try without passing that?
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
First of all Google Location Services are far better than Traditional LocationManager to achieve this requirement.
https://developer.android.com/training/location/request-updates
I have written an android app which basically allows me to keep track of times and address of GPS coordinates.
I have 3 Lists each corresponding to Lyft, Uber and Other.
But I believe my app starts slowing down my Smart Phone (Samsung Galaxy S7 Edge, with Android O)
can someone look at my code and tell me why is it slowing my smart phone.
My assumption is that, possibly thread synchronization issue.
Attached is my code
1) MainActivity.java
package com.milind.myapp.gpstrackingservice;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.PowerManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AddressListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private PowerManager.WakeLock wakeLock;
private TextView labelAddress;
private TextView multiTextLyft;
private TextView multiTextUber;
private TextView multiTextOther;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
labelAddress = findViewById(R.id.label_address);
multiTextLyft = findViewById(R.id.multi_text_lyft);
multiTextUber = findViewById(R.id.multi_text_uber);
multiTextOther = findViewById(R.id.multi_text_other);
if (MyService.isServiceStarted())
{
MyService.getInstance().load(getSharedPrefs());
refreshAllViews();
}
PowerManager powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "myapp:My Lock");
}
#Override
protected void onStart()
{
super.onStart();
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WAKE_LOCK}, 1);
if (!MyService.isServiceStarted())
{
Intent intent = new Intent(this, MyService.class);
intent.setAction(MyService.ACTION_START_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
startForegroundService(intent);
}
else
{
startService(intent);
}
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
if (MyService.isServiceStarted())
{
MyService.getInstance().registerAddressListener(this);
}
wakeLock.acquire();
}
else
{
if (MyService.isServiceStarted())
{
MyService.getInstance().unregisterAddressListener(this);
}
wakeLock.release();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults)
{
switch (requestCode)
{
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location loc)
{
final String address = MyService.getAddress(this, loc);
final CharSequence text = labelAddress.getText();
if (text.toString().equals(address))
{
return;
}
MyService.getInstance().load(getSharedPrefs());
labelAddress.setText(address);
refreshAllViews();
new Tone().play(880);
}
private void refreshAllViews()
{
runOnUiThread(new Runnable()
{
public void run()
{
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
});
}
private void refereshEditTextLyft()
{
multiTextLyft.setText(MyService.getInstance().getLyftAddresses());
}
private void refereshEditTextUber()
{
multiTextUber.setText(MyService.getInstance().getUberAddresses());
}
private void refereshEditTextOther()
{
multiTextOther.setText(MyService.getInstance().getOtherAddresses());
}
private SharedPreferences getSharedPrefs()
{
return getSharedPreferences("name", MODE_PRIVATE);
}
public void onLyftButtonClicked(View view)
{
MyService.getInstance().addLyftAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onUberButtonClicked(View view)
{
MyService.getInstance().addUberAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onOtherButtonClicked(View view)
{
MyService.getInstance().addOtherAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
public void onClearButtonClicked(View view)
{
if (MyService.isServiceStarted())
{
SharedPreferences sharedPreferences = getSharedPrefs();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
MyService.getInstance().clear();
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
}
public void onDelLyftButtonClicked(View view)
{
MyService.getInstance().delLyftEntry();
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelUberButtonClicked(View view)
{
MyService.getInstance().delUberEntry();
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelOtherButtonClicked(View view)
{
MyService.getInstance().delOtherEntry();
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
public void onActionModeFinished(ActionMode mode)
{
super.onActionModeFinished(mode);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
}
2) The MyService.java
package com.milind.myapp.gpstrackingservice;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MyService extends Service implements LocationListener
{
private static final String TAG = MyService.class.getSimpleName();
public static final String ACTION_START_SERVICE = "ACTION_START_SERVICE";
public static final String ACTION_STOP_SERVICE = "ACTION_STOP_SERVICE";
public static final String ACTION_UBER = "ACTION_UBER";
public static final String ACTION_LYFT = "ACTION_UBER";
public static final String ACTION_END = "ACTION_END";
public static final String LYFT_PREFIX = "Lyft";
public static final String OTHER_PREFIX = "Other";
public static final String UBER_PREFIX = "Uber";
private static MyService mInstance = null;
private List<AddressListener> listeners = new ArrayList<>();
private List<AddressPoint> lyftAddresses = new ArrayList<>();
private List<AddressPoint> uberAddresses = new ArrayList<>();
private List<AddressPoint> otherAddresses = new ArrayList<>();
private Location mLastLocation;
public MyService()
{
super();
Log.d(TAG, "MyService(): constructor called");
}
public static boolean isServiceStarted()
{
Log.d(TAG, "isServiceStarted()");
return mInstance != null;
}
public static final MyService getInstance()
{
return mInstance;
}
#Override
public IBinder onBind(Intent intent)
{
Log.d(TAG, "onBind(Intent intent)");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand(Intent, flags, startId) : " + hashCode());
Log.d(TAG, "onStartCommand(...) intent=" + intent + "=" + ", flags=" + flags + ", startId=" + startId);
Log.d(TAG, "onStartCommand(...) isServiceStarted=" + isServiceStarted());
String action = null;
if (intent != null)
{
Log.d(TAG, intent.toString());
action = intent.getAction();
}
else
{
Log.d(TAG, "onStartCommand(...): early return");
return super.onStartCommand(intent, flags, startId);
}
if (isServiceStarted() == false && action == ACTION_START_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service starting=" + startId);
//startForegroundServivceNotification()
startRunningInForeground();
requestLocationUpdates();
mInstance = this;
Log.d(TAG, "onStartCommand(...): Service started=" + startId);
}
else if (isServiceStarted() == true && action == ACTION_STOP_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service stopping=" + startId);
stopLocationUpdates();
stopSelf();
Log.d(TAG, "onStartCommand(...): Service stop requested" + startId);
mInstance = null;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
Log.d(TAG, "onDestroy(): Service destroyed");
super.onDestroy();
mInstance = null;
}
private void stopLocationUpdates()
{
Log.d(TAG, "stopLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
private void requestLocationUpdates()
{
Log.d(TAG, "requestLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1500, 0, this);
Log.w(TAG, "requestLocationUpdates(): ended gracefully");
}
catch (SecurityException ex)
{
Log.w(TAG, "requestLocationUpdates(): Exception");
ex.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location)
{
Log.v(TAG, "onLocationChanged(Location location): started, location=" + location.toString());
dispatchLocationChange(location);
mLastLocation = location;
Log.v(TAG, "onLocationChanged: completed");
}
private void dispatchLocationChange(Location loc)
{
Log.v(TAG, "dispatchLocationChange(Location)");
for (AddressListener listener : listeners)
{
listener.onLocationChanged(loc);
}
}
public static String getAddress(Context context, Location loc)
{
Log.v(TAG, "getAddress(Location loc) started");
List<Address> addresses;
Geocoder gcd = new Geocoder(context, Locale.getDefault());
try
{
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
String strReturnAddress = "";
if (addresses != null && addresses.size() > 0)
{
final Address address = addresses.get(0);
Log.d(TAG, address.toString());
String addressLines = "";
Log.v(TAG, "Locale: " + address.getLocale());
for (int i = 0; i <= address.getMaxAddressLineIndex(); ++i)
{
Log.v(TAG, "AddressLine " + i + ": " + address.getAddressLine(i));
addressLines += address.getAddressLine(i) + ", ";
Log.v(TAG, "addressLines:" + addressLines);
}
String strAddress =
addressLines
;
Log.v(TAG, "strAddress:" + strAddress);
strReturnAddress = strAddress.substring(0, strAddress.length() - 2);
Log.v(TAG, "strReturnAddress:" + strReturnAddress);
}
Log.d(TAG, "getAddress(Location loc) completed with return=" + strReturnAddress);
return strReturnAddress;
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, "Exception", e);
}
Log.d(TAG, "getAddress(Location loc) completed with return=null");
return "";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.d(TAG, "onStatusChanged(provider, status, extras): status=" + status + ", extras=" + extras);
}
#Override
public void onProviderEnabled(String provider)
{
Log.d(TAG, "onProviderEnabled(provider) ");
}
#Override
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled(provider) ");
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private static void logGetProperties(final String tag, final Object obj)
{
Log.v(tag, "logGetProperties(...)");
Class cls = obj.getClass();
Method[] methods = cls.getMethods();
Log.v(tag, "methods.length = " + methods.length);
for (Method method : methods)
{
String methodName = method.getName();
Log.v(tag, "methodName = " + methodName);
if (methodName.startsWith("get")
&& (method.getParameters() == null || method.getParameters().length == 0)
&& method.getReturnType() != Void.class)
{
try
{
Log.v(tag, methodName + " = " + method.invoke(obj, new Object[0]));
}
catch (Exception ex)
{
Log.e(tag, methodName + " Failed (exception)");
}
}
}
}
public AddressListener registerAddressListener(AddressListener listener)
{
Log.d(TAG, "registerAddressListener(AddressListener)");
if (!listeners.contains(listener))
{
listeners.add(listener);
}
return listener;
}
public AddressListener unregisterAddressListener(AddressListener listener)
{
Log.d(TAG, "unregisterAddressListener(AddressListener)");
if (listeners.contains(listener))
{
listeners.remove(listener);
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener removed");
return listener;
}
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener not found");
return null;
}
public void addLyftAddress(CharSequence text)
{
Log.d(TAG, "addLyftAddress(CharSequence text): text: " + text);
lyftAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addUberAddress(CharSequence text)
{
Log.d(TAG, "addUberAddress(CharSequence text): text: " + text);
uberAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addOtherAddress(CharSequence text)
{
Log.d(TAG, "addOtherAddress(CharSequence text): text: " + text);
otherAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
String getLyftAddresses()
{
return getAddresses(lyftAddresses);
}
String getUberAddresses()
{
return getAddresses(uberAddresses);
}
String getOtherAddresses()
{
return getAddresses(otherAddresses);
}
private String getAddresses(List<AddressPoint> addresses)
{
Log.d(TAG, "getAddresses(List<AddressPoint>)");
String strAddresses = "" + addresses.size() + "\n--------\n";
for (int i = 0; i < addresses.size(); ++i)
{
AddressPoint addresspoint = addresses.get(i);
strAddresses += addresspoint + "\n--------\n";
if ((i % 2) != 0)
{
strAddresses += "\n\n";
}
}
return strAddresses;
}
private void startRunningInForeground()
{
//if more than or equal to 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
//if more than 26
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
{
String CHANNEL_ONE_ID = "Package.Service";
String CHANNEL_ONE_NAME = "Screen service";
NotificationChannel notificationChannel = null;
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null)
{
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle("Recording data")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(101, notification);
}
//if version 26
else
{
startForeground(101, updateNotification());
}
}
//if less than version 26
else
{
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("App")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setOngoing(true).build();
startForeground(101, notification);
}
}
private Notification updateNotification()
{
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
return new NotificationCompat.Builder(this)
.setContentTitle("Activity log")
.setTicker("Ticker")
.setContentText("app is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setOngoing(true).build();
}
public void load(final SharedPreferences lSharedPrefs)
{
Log.w(TAG, "load(SharedPreferences): started");
load(lSharedPrefs, lyftAddresses, LYFT_PREFIX);
load(lSharedPrefs, uberAddresses, UBER_PREFIX);
load(lSharedPrefs, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "load(SharedPreferences): completed");
}
private void load(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "load(SharedPreferences, lAddrPoints, lPrefix)");
lAddrPoints.clear();
final int count = lSharedPrefs.getInt(lPrefix + "Count", lAddrPoints.size());
for (int i = 0; i < count; ++i)
{
String address = lSharedPrefs.getString(lPrefix + "Address" + i, null);
final long time = lSharedPrefs.getLong(lPrefix + "Time" + i, 0);
//if address or time is invalid skip to the next entry
if (address == null || time == 0)
{
continue;
}
final AddressPoint addressPoint = new AddressPoint(time, address);
lAddrPoints.add(addressPoint);
}
}
private void save(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "save(SharedPreferences, lAddrPoints, lPrefix)");
SharedPreferences.Editor editor = lSharedPrefs.edit();
final int count = lAddrPoints.size();
//Save the count
editor.putInt(lPrefix + "Count", count);
for (int i = 0; i < count; ++i)
{
//Save the entry
AddressPoint lAddrPoint = lAddrPoints.get(i);
editor.putLong(lPrefix + "Time" + i, lAddrPoint.getTime());
editor.putString(lPrefix + "Address" + i, (String) lAddrPoint.getAddress());
}
Log.w(TAG, "save(sharedFrefs, List, String): commit");
editor.commit();
}
public void save(final SharedPreferences sharedPreferences)
{
Log.w(TAG, "save(SharedPreferences): started");
Log.w(TAG, "save: lyftAddresses");
save(sharedPreferences, lyftAddresses, LYFT_PREFIX);
Log.w(TAG, "save: uberAddresses");
save(sharedPreferences, uberAddresses, UBER_PREFIX);
Log.w(TAG, "save: otherAddresses");
save(sharedPreferences, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "save(SharedPreferences) completed");
}
public void clear()
{
lyftAddresses.clear();
uberAddresses.clear();
otherAddresses.clear();
}
public void delLyftEntry()
{
if (lyftAddresses.size() > 0)
{
lyftAddresses.remove(lyftAddresses.size() - 1);
}
}
public void delUberEntry()
{
if (uberAddresses.size() > 0)
{
uberAddresses.remove(uberAddresses.size() - 1);
}
}
public void delOtherEntry()
{
if (otherAddresses.size() > 0)
{
otherAddresses.remove(otherAddresses.size() - 1);
}
}
}
3) activity_main.xml
4) AndroidManifest.xml
This (likely) isn't a threading issue, in the normal sense of the word. What's happening is you've got a GeoCoder.getFromLocation() call executing on the main thread. Per the documentation:
The returned values may be obtained by means of a network lookup. ...It may be useful to call this method from a thread separate from your primary UI thread.
That means the method could block for several seconds each time it is called. That's more likely if you're driving through an area of spotty cell coverage. Since the method is called with each location update (roughly every 2 seconds), it's understandable that the UI is hanging.
SUGGESTED FIX
Replace your getAddress() function with an AsyncTask, which moves the getFromLocation() call to a background thread (now your app will truly be multithreaded). Something like this should work:
private class GetFromLocationTask extends AsyncTask<Location, Void, List<Address>> {
protected List<Address> doInBackground(Location... locs) {
return gcd.getFromLocation(locs[ 0 ].getLatitude(), locs[ 0 ].getLongitude(), 1);
}
protected void onProgressUpdate(Void... progress) {}
protected void onPostExecute(List<Address> result) {
//execute the remainder of your getAddress() logic here
}
}
Then, execute it using new GetFromLocationTask().execute(location). Call this instead of getAddress(). You don't need to pass a Context to getAddress(), since Service.this will work just as well (it is a Context).
Bonus hint: Note that onLocationChanged() runs on the UI thread, and so does refreshAllViews(). That means your call to runOnUiThread() is superfluous, and it will just execute the given Runnable synchronously.
I have made a location update foreground service which gets locations directly(requestLocationUpdates) when interval is less than 30 secs and if its more than 30 sec, I use ScheduledExecutorService to get the location result and pool location results to get the best location. Only issue I am facing is I am not getting location updates when screen goes off. This code is working well till mobile screen goes off.
Please take care its a foreground service.
My Code is as below:
private boolean currentlyProcessingLocation = false;
public static int intervalForLocationRequestMethod = 500;
public static int intervalForLocationUpdates = 30000;
public int locationUpdateMethodThreshold = 5000;
public int sameLocationCounter = 0;
boolean locationUpdateMethodChanged = false;
ScheduledExecutorService sch;
Runnable periodicTask = new Runnable() {
#Override
public void run() {
Log.i(TAG, "run: repeat ");
Intent i = new Intent(LocationService.this, LocationService.class);
i.setAction(Constants.ACTION.STARTLOCATIONREPEAT_ACTION);
startService(i);
}
};
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
buildGoogleApiClient();
if (intervalForLocationUpdates <= locationUpdateMethodThreshold) {
intervalForLocationRequestMethod = intervalForLocationUpdates;
}
showOnGoingLocationServiceNotification();
}
private void showOnGoingLocationServiceNotification() {
Log.i(TAG, "showOnGoingLocationServiceNotification: ");
Intent notificationIntent = new Intent(this, MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Forcee")
.setTicker("Forcee Tracking")
.setColor(Color.GREEN)
.setContentText("Forcee is tracking your location....Tap to stop")
.setSmallIcon(R.drawable.cast_ic_notification_small_icon)
.setWhen(System.currentTimeMillis())
.setContentIntent(resultPendingIntent)
.setOngoing(true).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setFastestInterval(intervalForLocationRequestMethod);
mLocationRequest.setInterval(intervalForLocationRequestMethod);
if (intervalForLocationUpdates <= locationUpdateMethodThreshold || locationUpdateMethodChanged) {
mLocationRequest.setSmallestDisplacement(50);
}
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
Thread thread = new Thread(new LocationUpdateThread(intent, startId));
thread.start();
return START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
if (lastLocation != null) {
if (location.distanceTo(lastLocation) >= 40.0f && locationUpdateMethodChanged && location.getAccuracy() <= 100.0f) {
locationUpdateMethodChanged = false;
currentlyProcessingLocation = false;
sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
sch.scheduleAtFixedRate(periodicTask, intervalForLocationUpdates, intervalForLocationUpdates, TimeUnit.MILLISECONDS);
}
}
if (location.getAccuracy() <= 100.0f) {
if (firstLocationUpdateCall) {
updatingLocation(location);
firstLocationUpdateCall = false;
} else {
if (location.distanceTo(lastLocation) >= 40.0f) {
updatingLocation(location);
sameLocationCounter = 0;
} else {
if (intervalForLocationUpdates > locationUpdateMethodThreshold && !locationUpdateMethodChanged) {
sameLocationCounter++;
lastLocation = location;
Log.i(TAG, "onLocationChanged: " + sameLocationCounter);
if (sameLocationCounter == 5) {
locationUpdateMethodChanged = true;
intervalForLocationRequestMethod = 1000;
stopLocationUpdates();
sameLocationCounter = 0;
sch.shutdownNow();
sch = null;
Intent i = new Intent(LocationService.this, LocationService.class);
i.setAction(Constants.ACTION.STARTLOCATIONREPEAT_ACTION);
startService(i);
}
Log.i(TAG, "onLocationChanged: " + locationUpdateMethodChanged);
}
}
if (intervalForLocationUpdates> locationUpdateMethodThreshold && !locationUpdateMethodChanged) {
stopLocationUpdates();
Log.i(TAG, "onLocationChanged: stopcheckshift");
}
}
}
}
public void updatingLocation(Location location) {
lastLocation = location;
Log.i(TAG, "onLocationChanged: First " + locationPoints.size());
locationPoints.add(location);
Log.i(TAG, "onLocationChanged: Last " + locationPoints.size());
sendLocationsToActivity(locationPoints);
if (intervalForLocationUpdates > locationUpdateMethodThreshold) {
stopLocationUpdates();
}
}
public void sendLocationsToActivity(ArrayList<Location> locationPoints) {
Log.i(TAG, "sendLocationsToActivity: ");
Intent intent = new Intent("LocationUpdates");
intent.putParcelableArrayListExtra("Locations", locationPoints);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void stopLocationUpdates() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, LocationService.this);
mGoogleApiClient.disconnect();
currentlyProcessingLocation = false;
}
}
final class LocationUpdateThread implements Runnable {
int service_id;
Intent intent;
LocationUpdateThread(Intent intent, int service_id) {
this.intent = intent;
this.service_id = service_id;
}
#Override
public void run() {
Log.i(TAG, "run: ");
if (intent != null) {
Log.i(TAG, "run: " + intent.getAction());
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
toastHandler("Tracking Started!");
mGoogleApiClient.connect();
currentlyProcessingLocation = true;
if (intervalForLocationUpdates > locationUpdateMethodThreshold) {
sch = Executors.newScheduledThreadPool(1);
sch.scheduleAtFixedRate(periodicTask, intervalForLocationUpdates, intervalForLocationUpdates, TimeUnit.MILLISECONDS);
}
} else if (intent.getAction().equals(Constants.ACTION.STARTLOCATIONREPEAT_ACTION)) {
if (!currentlyProcessingLocation) {
Log.i(TAG, "run: curt");
checkLocationSettings();
currentlyProcessingLocation = true;
mGoogleApiClient.connect();
}
} else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, LocationService.this);
mGoogleApiClient.disconnect();
}
if (sch != null) {
sch.shutdownNow();
}
stopForeground(true);
stopSelf();
toastHandler("Tracking Stopped!");
}
}
}
void toastHandler(final String msg) {
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
Toast.makeText(LocationService.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
I am using geofence api for proximity but it is not working properly. some times it gives in range and out range at the same location.
i am also using GPS library to improve accuracy of geofence inrange-outrange but still it is not working properly. i am using below code for geofence :
I am using 300 meters radius for considering inrange-outrange (enter-exit)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geofencedemo">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CheckPermission"
android:screenOrientation="portrait"
android:theme="#style/DialogActivity" />
<receiver
android:name="services.GeofenceTransitionsReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.geofencedemo.ACTION_RECEIVE_GEOFENCE" />
<category android:name="com.geofencedemo" />
</intent-filter>
</receiver>
<service
android:name="services.GeofenceTransitionsIntentService"
android:exported="false" />
</application>
MainActivity.java (for registering geofence)
public class MainActivity extends Activity implements com.google.android.gms.location.LocationListener {
private LocationManager locationManager;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private final float GEOFENCE_RADIUS_IN_METERS = 300;//Meter(s)
private final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = Geofence.NEVER_EXPIRE;
private int GEOFENCE_TRANSITION_ENTER = 1;
private int GEOFENCE_TRANSITION_EXIT = 2;
private List<Geofence> mGeofenceList;
private String geofenceID = "testGeofence";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("ISSKEYGEOFENCE-prefs", MODE_PRIVATE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Button btnSetLocation = (Button) findViewById(R.id.btn_setlocation);
btnSetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
Toast.makeText(getApplicationContext(), "Please enable Location service to allow set location", Toast.LENGTH_LONG).show();
return;
}
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1){
Log.d("myTag", "check marshmallow permission...");
Intent permissionIntent = new Intent(MainActivity.this, CheckPermission.class);
startActivityForResult(permissionIntent, 1111);
} else {
intGoogleAPI();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1111:
if (resultCode == RESULT_OK) {
intGoogleAPI();
}
break;
}
}
private void intGoogleAPI() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
mGeofenceList = new ArrayList<Geofence>(1);
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(final Bundle bundle) {
if (isServiceConnected()) {
Log.d("myTag", "request for update current location");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
}
#Override
public void onConnectionSuspended(final int cause) {}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(final ConnectionResult connectionResult) {}
}).build();
mGoogleApiClient.connect();
}
private boolean isServiceConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
return ConnectionResult.SUCCESS == resultCode;
}
#Override
public void onLocationChanged(Location mLastLocation) {
if (isServiceConnected()) {
Log.d("myTag", "request removed location update");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
addLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude());
} catch (Exception e) {}
}
public void addLocation(final double latitude, final double longitude) {
Log.v("myTag", "set lcation lat: " + latitude);
Log.v("myTag", "set lcation lag: " + longitude);
mGeofenceList.add(new Geofence.Builder().setRequestId(geofenceID).setTransitionTypes(GEOFENCE_TRANSITION_ENTER | GEOFENCE_TRANSITION_EXIT).setCircularRegion(latitude, longitude, GEOFENCE_RADIUS_IN_METERS).setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS).build());
final List<String> GEO_FENCE_ID_LIST = new ArrayList<String>();
GEO_FENCE_ID_LIST.add(geofenceID);
if (mGoogleApiClient != null) {
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, GEO_FENCE_ID_LIST).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(final Status status) {
if (status.isSuccess()) {
// successfully removed geofence...
Log.d("myTag", "removed old geofence successfully ");
} else {
Log.d("myTag", "Not removed old geofence");
}
}
});
}
if (mGoogleApiClient != null) {
LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(final Status status) {
if (status.isSuccess()) {
// successfully Added geofence...
Log.d("myTag", "New geofence successfully added");
Toast.makeText(getApplicationContext(), "Successfully added geofence", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", false);
editor.putString("lat", String.valueOf(latitude));
editor.putString("log", String.valueOf(longitude));
editor.apply();
}
try {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
mGoogleApiClient.disconnect();
} catch (Exception e) {}
}
});
}
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent("com.geofencedemo.ACTION_RECEIVE_GEOFENCE");
return PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
GeofenceTransitionsIntentService (Trigger inrange,outrange by geofence)
public class GeofenceTransitionsIntentService extends IntentService implements com.google.android.gms.location.LocationListener {
public GeofenceTransitionsIntentService() {
super("GeofenceTransitionsIntentService");
}
#Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences("ISSKEYGEOFENCE-prefs", MODE_PRIVATE);
}
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private boolean isLocationFetched = false;
private String geofenceTransitionIds;
private boolean isInRange = false;
private SharedPreferences preferences;
#Override
protected void onHandleIntent(final Intent intent) {
if (intent.getExtras() != null) {
int geofenceTransitionType = intent.getIntExtra("TransitionType", 4);
geofenceTransitionIds = intent.getStringExtra("TransitionId");
/*final String lat = intent.getStringExtra("TransitionId_lat");
final String log = intent.getStringExtra("TransitionId_log");*/
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
switch (geofenceTransitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
geofenceTransitionIds(geofenceTransitionIds, true);
//new IntGoogleApiClient(appStorage, null, true).Intialize();
//processIn(geofenceTransitionIds, lat, log);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
geofenceTransitionIds(geofenceTransitionIds, false);
//new IntGoogleApiClient(appStorage, null, true).Intialize();
//processOut(geofenceTransitionIds, lat, log);
break;
}
}
}
}
private void geofenceTransitionIds (String geofenceTransitionIds, boolean isEnteCall) {
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
isInRange = isEnteCall;
intGoogleAPI();
}
}
private void intGoogleAPI() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
mGoogleApiClient = new GoogleApiClient.Builder(GeofenceTransitionsIntentService.this).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(final Bundle bundle) {
if (isServiceConnected()) {
// please consider here location permission is already allowed...
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, GeofenceTransitionsIntentService.this);
}
}
#Override
public void onConnectionSuspended(final int cause) {}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(final ConnectionResult connectionResult) {}
}).build();
mGoogleApiClient.connect();
}
private boolean isServiceConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(GeofenceTransitionsIntentService.this);
return ConnectionResult.SUCCESS == resultCode;
}
#Override
public void onLocationChanged(Location passedLocation) {
if (passedLocation != null && !isLocationFetched) {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, GeofenceTransitionsIntentService.this);
}
isLocationFetched = true;
try {
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
if (isInRange) {
processIn(geofenceTransitionIds, String.valueOf(passedLocation.getLatitude()), String.valueOf(passedLocation.getLongitude()));
} else {
processOut(geofenceTransitionIds, String.valueOf(passedLocation.getLatitude()), String.valueOf(passedLocation.getLongitude()));
}
}
} catch (Exception e) {}
disconnectGoogleClient();
}
}
private void disconnectGoogleClient() {
try {
if (mGoogleApiClient != null) {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, GeofenceTransitionsIntentService.this);
}
mGoogleApiClient.disconnect();
}
} catch (Exception e) {}
}
private void processIn(String passedIds, String lat, String log) {
if (passedIds != null) {
List<String> items = Arrays.asList(passedIds.split("\\s*,\\s*"));
for (String deviceName : items) {
if (deviceName != null) {
boolean isOutRange = preferences.getBoolean("isinrange", false);
if (mappingRadius(true, deviceName, lat, log) && isOutRange) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", false);
editor.apply();
sendNotification(GeofenceTransitionsIntentService.this, "In range come!", Color.BLACK);
}
}
}
}
}
private void processOut(String passedIds, String lat, String log) {
if (passedIds != null) {
List<String> items = Arrays.asList(passedIds.split("\\s*,\\s*"));
for (String deviceName : items) {
if (deviceName != null) {
boolean isInRange = preferences.getBoolean("isinrange", false);
if (mappingRadius(false, deviceName, lat, log) && !isInRange) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", true);
editor.apply();
sendNotification(GeofenceTransitionsIntentService.this, "Out range come!", Color.RED);
}
}
}
}
}
private boolean mappingRadius(boolean isInRange, String deviceName, String currentLat, String currentLog) {
final float cLat = Float.parseFloat(currentLat);
final float cLog = Float.parseFloat(currentLog);
Log.d("myTag", "GeofenceTransitionsReceiver lat " + cLat);
Log.d("myTag", "GeofenceTransitionsReceiver log " + cLog);
float appLat;
float appLog;
appLat = Float.parseFloat(preferences.getString("lat", "0.0"));
appLog = Float.parseFloat(preferences.getString("log", "0.0"));
Log.d("myTag", "GeofenceTransitionsReceiver app lat " + appLat);
Log.d("myTag", "GeofenceTransitionsReceiver app log " + appLog);
Location current_latlog = new Location("crntlocation");
current_latlog.setLatitude(appLat);
current_latlog.setLongitude(appLog);
Location new_latlog = new Location("newlocation");
new_latlog.setLatitude(cLat);
new_latlog.setLongitude(cLog);
final double distance = current_latlog.distanceTo(new_latlog);
Log.v("myTag", "GeofenceTransitionsReceiver calculation distance is: " + distance);
//if (distance < 2000) {
if (isInRange) {
if (distance <= 300) { // with in 300 Meters consider as in range...
return true;
} else {
return false;
}
} else {
if (distance >= 300) { // more than 300 Meters consider as out range...
return true;
} else {
return false;
}
}
/*} else {
return false;
}*/
}
private void sendNotification(final Context context, String notificationMessage, int color) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(new Intent());
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)).setContentTitle(context.getResources().getString(R.string.app_name)).setTicker(notificationMessage).setContentText(notificationMessage).setContentIntent(notificationPendingIntent).setColor(color).setVibrate(new long[] { 1000, 1000, 1000, 1000 }).setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int) System.currentTimeMillis(), builder.build());
}
}
GeofenceTransitionsReceiver (handling/calculate distance after geofence trigger)
public class GeofenceTransitionsReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = getErrorString(context, geofencingEvent.getErrorCode());
Log.d("myTag", "GeofenceTransitionsReceiver error " +errorMessage);
// sendNotification(context, errorMessage, Color.RED);
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.d("myTag", "GeofenceTransitionsReceiver " + geofenceTransition);
// for testing....
//sendNotification(context, context.getResources().getString(R.string.geofence_transition_type, geofenceTransition), Color.RED);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
String geofenceTransitionIds = getGeofenceTransitionIds(triggeringGeofences);
Location triggeringLocation = geofencingEvent.getTriggeringLocation();
Intent serviceIntent = new Intent(context.getApplicationContext(), GeofenceTransitionsIntentService.class);
serviceIntent.putExtra("TransitionType", geofenceTransition);
serviceIntent.putExtra("TransitionId", geofenceTransitionIds);
serviceIntent.putExtra("TransitionId_lat", String.valueOf(triggeringLocation.getLatitude()));
serviceIntent.putExtra("TransitionId_log", String.valueOf(triggeringLocation.getLongitude()));
context.startService(serviceIntent);
} else {
// sendNotification(context,
// context.getResources().getString(R.string.geofence_transition_invalid_type,
// geofenceTransition), Color.RED);
}
}
private String getErrorString(final Context context, int errorCode) {
Resources mResources = context.getResources();
switch (errorCode) {
case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
return "Geofence service is not available now";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
return "Your app has registered too many geofences";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "You have provided too many PendingIntents to the addGeofences() call";
default:
return "Unknown error: the Geofence service is not available now";
}
}
private String getGeofenceTransitionIds(List<Geofence> triggeringGeofences) {
List<String> triggeringGeofencesIdsList = new ArrayList<String>();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
return TextUtils.join(",", triggeringGeofencesIdsList);
}
}
Is there anything else we can do to improve accuracy and overcome the problem of inrange outrange at the same location ?
I want to Current location and sent that location on my ASP.Net Web service.
I write following code.
Background Service is start by using this code but i don`t get Location.
OnLocationChange() Method is not called.
Please Help me.
Following Code:
Set Alarm Code:
#TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean AlarmSet(Context context, String function, AlarmManager alarmMan) {
AlarmManager alarmManager = alarmMan;
PendingIntent pending_intent;
DatabaseHandler DB;
try {
DB = new DatabaseHandler(context);
String state = function;
final Intent myIntent = new Intent(context, AlarmReceiver.class);
final Calendar calendar = Calendar.getInstance();
if (state.contains("setall")) {
String result = DB.ConvStrSelctTripTimeDetails();
String[] row = result.split("####");
for (int i = 0; i < row.length; i++) {
String[] data = row[i].split("#");
int rowid = Integer.parseInt(data[0]);
int shiftid = Integer.parseInt(data[1]);
int dayid = Integer.parseInt(data[2]);
if (dayid != 7) {
dayid = dayid + 1;
} else {
dayid = 1;
}
String[] strtIN = data[3].split(":");
String[] endIN = data[4].split(":");
String[] strtOUT = data[5].split(":");
String[] endOUT = data[6].split(":");
String alarmStartIN = "1";
//IN_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "1";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//IN_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "2";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "3";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "4";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
}
return true;
} catch (Exception ex) {
common.writelog("common", "AlarmSet() Value:"+ function +": Error:361:" + ex.getMessage());
Log.e("common", "onCreate() Value:"+ function +": Error:361:" + ex.getMessage());
return false;
}
}
AlarmReceiver File Code:
public class AlarmReceiver extends BroadcastReceiver {
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
#Override
public void onReceive(Context context, Intent intent) {
String ShiftID = intent.getExtras().getString("ShiftID");
Log.e("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
if(context==null)
{
Log.e("AlarmReceiver","Context:null");
}
else
{
Log.e("AlarmReceiver","Context:Not null");
}
String ops = intent.getExtras().getString("ops");
Log.e("AlarmReceiver", "onReceive() ops : " + ops);
common.writelog("AlarmReceiver", "onReceive() ops : " + ops);
if (ops.equals("s")) {
try {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean statusOfGPS = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*
* if (!statusOfGPS) { showGPSDisabledAlertToUser(); }
*/
// startAt10();
// start();
common.Running = true;
buildGoogleApiClient(context);
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception ex) {
Log.e("AlarmReceiver", "onReceive() Error: 48 : " + ex.getMessage());
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ex.getMessage());
}
Log.e("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.startService(serviceIntent);
//context.startService(new Intent(context, MyService.class));
} else if (ops.equals("e")) {
Log.e("AlarmReceiver", "onReceive() End Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() End Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.stopService(serviceIntent);
}
}
protected synchronized void buildGoogleApiClient(Context contex) {
mGoogleApiClient = new GoogleApiClient.Builder(contex)
.addApi(LocationServices.API).build();
createLocationRequest();
}
private void createLocationRequest() {
try {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest
.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}catch (Exception ex)
{
common.writelog("AlarmReceiver", "createLocationRequest()86: " + ex.getMessage());
}
}
}
MyService Code:
package com.expedite.apps.vehiclelocation;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.format.Time;
import android.util.Log;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 2f;
private static String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION_VISITED = "http://tempuri.org/setVechicleLocation";
private static String METHOD_SEND_LOCATION_DATA = "setVechicleLocation";
private static String URL = "http://vts.vayuna.com/Service.asmx";
public String buskey = "";
boolean isget = false;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
try {
Log.e(TAG, "LocationListener " + provider);
common.writelog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
} catch (Exception ex) {
Log.d(TAG, "LocationListener() Error:48 " + ex.getMessage());
common.writelog(TAG, "LocationListener() Error:48 " + ex.getMessage());
}
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
try {
mLastLocation.set(location);
Time time = new Time();
time.setToNow();
if (common.lat != location.getLatitude() || common.lon != location.getLongitude() || common.minut != time.minute) {
common.lat = location.getLatitude();
common.lon = location.getLongitude();
common.accu = location.getAccuracy();
common.minut = time.minute;
common.time = time.hour + ":" + time.minute + ":" + time.second;
new MyTask().execute();
common.writelog(TAG, "onLocationChanged: " + location.getAccuracy());
} else {
}
// Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
common.writelog(TAG, "onStatusChanged: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
common.writelog(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
common.writelog(TAG, "onProviderDisabled: " + provider);
}
}
/* LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};*/
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER)
};
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Log.e(TAG, "onStartCommand");
common.writelog(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
} catch (Exception ex) {
Log.d(TAG, "onStartCommand() Error:120 " + ex.getMessage());
common.writelog(TAG, "onStartCommand() Error:120 " + ex.getMessage());
return 0;
}
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
DatabaseHandler DB = new DatabaseHandler(getApplicationContext());
String Res = DB.ConvStrBusMaster();
if (!Res.equals("")) {
try {
String[] respons = Res.split("####");
buskey = respons[3].toString();
Log.e("MyService", "onCreate() buskey"+buskey);
common.writelog("MyService", "onCreate() buskey"+buskey);
} catch (Exception ex) {
common.writelog("MyService::onCreate()", "Error: 121 MSG:" + ex.getMessage());
Log.e("MyService", "onCreate() Error: 121 MSG:" + ex.getMessage());
}
}
/* Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
if (isget == false) {
buskey =common.busid;
isget = true;
}*/
initializeLocationManager();
/* try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
common.writelog(TAG, "network provider does not exist, " + ex.getMessage());
}*/
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
common.writelog(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
try {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}catch ( Exception ex)
{
Log.d(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
common.writelog(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
}
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
SendDataToServer();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
public void SendDataToServer() {
// $,GJ05AV4839,4503791073,140416111538,21.172227,72.849145,0,0,0,0,#
SoapObject request = new SoapObject(NAMESPACE,
METHOD_SEND_LOCATION_DATA);
Time time = new Time();
String LocationDetails = "";
try {
if (common.lat != 0.0 && common.lon != 0.0) {
time.setToNow();
String m_androidId = "Service "
+ Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy:HH:mm:ss");
String currentTimeStamp = dateFormat.format(new Date());
/*LocationDetails = "$,XPD55," + time.hour + ":" + time.minute
+ ":" + time.second + "," + common.time + " Accuracy:"
+ common.accu + "," + common.lat + "," + common.lon
+ ",0,0,0," + m_androidId + ",#";*/
LocationDetails="$," + buskey + "," + buskey + "," + currentTimeStamp + "," + common.lat + ","
+ common.lon + ",0,0,Accuracy:" + common.accu + ",0,#";
common.writelog("Service", "SendLocation() 311:"+ common.lat+","+ common.lon+","+common.accu+", Details::"+LocationDetails+" , Url:"+URL);
request.addProperty("vehicleinfo", LocationDetails);
request.addProperty("device", buskey);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,
100000);
androidHttpTransport.call(SOAP_ACTION_VISITED, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
common.writelog("MyService","SendDataToServer()"+LocationDetails);
}
} catch (Exception ex) {
common.writelog("Service", "Exception 288:" + ex.getMessage()
+ ":::/n" + ex.getStackTrace());
}
}
}