cordova-plugin-mserviceinterface-2.0 1.0.26 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/package.json +28 -28
  2. package/plugin.xml +154 -153
  3. package/src/android/CallbackProgressDialog.java +53 -53
  4. package/src/android/FileProvider.java +7 -7
  5. package/src/android/backgroundNotification.java +120 -120
  6. package/src/android/doubleogradle.gradle +5 -5
  7. package/src/android/mInterface.java +2206 -2087
  8. package/src/android/mInterfaceReceiver.java +59 -59
  9. package/src/android/mInterfaceService.java +752 -749
  10. package/src/android/mInterfaceUtil.java +1686 -1686
  11. package/src/android/res/xml/network_security_config.xml +8 -8
  12. package/src/android/res/xml/opener_paths.xml +16 -16
  13. package/src/ios/InternetConnection.h +64 -64
  14. package/src/ios/InternetConnection.m +242 -242
  15. package/src/ios/SSZipArchive.h +146 -146
  16. package/src/ios/SSZipArchive.m +1180 -1180
  17. package/src/ios/SSZipCommon.h +66 -66
  18. package/src/ios/UICKeyChainStore.h +64 -64
  19. package/src/ios/UICKeyChainStore.m +434 -434
  20. package/src/ios/XMLConverter.h +61 -61
  21. package/src/ios/XMLConverter.m +243 -243
  22. package/src/ios/ZipArchive.h +19 -19
  23. package/src/ios/aes/aes.h +270 -270
  24. package/src/ios/aes/aes_ni.c +687 -687
  25. package/src/ios/aes/aes_ni.h +59 -59
  26. package/src/ios/aes/aescrypt.c +301 -301
  27. package/src/ios/aes/aeskey.c +554 -554
  28. package/src/ios/aes/aesopt.h +776 -776
  29. package/src/ios/aes/aestab.c +418 -418
  30. package/src/ios/aes/aestab.h +173 -173
  31. package/src/ios/aes/brg_endian.h +127 -127
  32. package/src/ios/aes/brg_types.h +191 -191
  33. package/src/ios/aes/fileenc.c +145 -145
  34. package/src/ios/aes/fileenc.h +121 -121
  35. package/src/ios/aes/hmac.c +209 -209
  36. package/src/ios/aes/hmac.h +119 -119
  37. package/src/ios/aes/prng.c +155 -155
  38. package/src/ios/aes/prng.h +82 -82
  39. package/src/ios/aes/pwd2key.c +181 -181
  40. package/src/ios/aes/pwd2key.h +45 -45
  41. package/src/ios/aes/sha1.c +283 -283
  42. package/src/ios/aes/sha1.h +72 -72
  43. package/src/ios/mInterface.h +1 -0
  44. package/src/ios/mInterface.m +15 -3
  45. package/src/ios/minizip/crypt.c +146 -146
  46. package/src/ios/minizip/crypt.h +66 -66
  47. package/src/ios/minizip/ioapi.c +353 -353
  48. package/src/ios/minizip/ioapi.h +154 -154
  49. package/src/ios/minizip/ioapi_buf.c +452 -452
  50. package/src/ios/minizip/ioapi_buf.h +52 -52
  51. package/src/ios/minizip/ioapi_mem.c +167 -167
  52. package/src/ios/minizip/ioapi_mem.h +52 -52
  53. package/src/ios/minizip/minishared.c +292 -292
  54. package/src/ios/minizip/minishared.h +50 -50
  55. package/src/ios/minizip/unzip.c +2007 -2007
  56. package/src/ios/minizip/unzip.h +254 -254
  57. package/src/ios/minizip/zip.c +2007 -2007
  58. package/src/ios/minizip/zip.h +215 -215
  59. package/www/mInterface.js +3 -3
@@ -1,749 +1,752 @@
1
- package com.selfservit.util;
2
-
3
- import android.Manifest;
4
- import android.annotation.TargetApi;
5
- import android.app.AlarmManager;
6
- import android.app.Notification;
7
- import android.app.NotificationChannel;
8
- import android.app.NotificationManager;
9
- import android.app.PendingIntent;
10
- import android.app.Service;
11
- import android.content.Context;
12
- import android.content.Intent;
13
- import android.content.pm.PackageManager;
14
- import android.graphics.Color;
15
- import android.location.Location;
16
- import android.media.RingtoneManager;
17
- import android.net.ConnectivityManager;
18
- import android.net.NetworkInfo;
19
- import android.net.Uri;
20
- import android.os.AsyncTask;
21
- import android.os.Build;
22
- import android.os.Bundle;
23
- import android.os.Environment;
24
- import android.os.IBinder;
25
- import android.os.SystemClock;
26
- import android.support.annotation.NonNull;
27
- import android.support.annotation.Nullable;
28
- import android.support.annotation.RequiresApi;
29
- import android.support.v4.app.NotificationCompat;
30
-
31
- import com.google.android.gms.common.ConnectionResult;
32
- import com.google.android.gms.common.GooglePlayServicesUtil;
33
- import com.google.android.gms.common.api.GoogleApiClient;
34
- import com.google.android.gms.common.api.PendingResult;
35
- import com.google.android.gms.common.api.Status;
36
- import com.google.android.gms.location.LocationRequest;
37
- import com.google.android.gms.location.LocationServices;
38
-
39
- import org.json.JSONArray;
40
- import org.json.JSONException;
41
- import org.json.JSONObject;
42
- import org.w3c.dom.Document;
43
-
44
- import java.io.BufferedReader;
45
- import java.io.BufferedWriter;
46
- import java.io.File;
47
- import java.io.FileReader;
48
- import java.io.FileWriter;
49
- import java.io.IOException;
50
- import java.io.OutputStreamWriter;
51
- import java.net.HttpURLConnection;
52
- import java.net.URL;
53
- import java.text.DateFormat;
54
- import java.text.SimpleDateFormat;
55
- import java.util.Arrays;
56
- import java.util.Date;
57
- import java.util.Timer;
58
- import java.util.TimerTask;
59
-
60
- import javax.xml.parsers.DocumentBuilder;
61
- import javax.xml.parsers.DocumentBuilderFactory;
62
-
63
- import static com.selfservit.util.mInterfaceUtil.decrypt;
64
-
65
- @TargetApi(Build.VERSION_CODES.O)
66
- public class mInterfaceService extends Service implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
67
- public Timer setQueueInterval,
68
- setQueueToServerInterval,
69
- setTimerIntervel,
70
- setLocationTimeInterval;
71
- GoogleApiClient mGoogleApiClient;
72
- LocationRequest mLocationRequest;
73
- Location mCurrentLocation;
74
- String mLastUpdateTime;
75
- private static long MINIMUM_INTERVAL = 0;
76
- private static TimerTask setProcessIntervalObj;
77
- private static Timer setProcessInterval;
78
- private static Context context;
79
- public static boolean appStateTimerStatus = false;
80
- String notification_icon, notification_color, app_name;
81
- int imageResource, app_name_id, notification_color_id;
82
- String locationUpdateInd = "false";
83
- @ Override
84
- public IBinder onBind(Intent intent) {
85
- // TODO: Return the communication channel to the service.
86
- throw new UnsupportedOperationException("Not yet implemented");
87
- }
88
- @ Override
89
- @TargetApi(Build.VERSION_CODES.O)
90
- public int onStartCommand(Intent intent, int flags, int startId) {
91
- try {
92
- this.context = getApplicationContext();
93
- if (mInterfaceUtil.packageName.equals("")) {
94
- mInterfaceUtil.packageName = getApplicationContext().getPackageName().split("\\.")[2];
95
- }
96
- notification_icon = "@drawable/ic_notification";
97
- notification_color = "@color/notification_accent";
98
- app_name = "@string/app_name";
99
- imageResource = getResources().getIdentifier(notification_icon, null, getPackageName());
100
- app_name_id = getResources().getIdentifier(app_name, null, getPackageName());
101
- notification_color_id = getResources().getIdentifier(notification_color, null, getPackageName());
102
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
103
- String NOTIFICATION_CHANNEL_ID = "com.selfservit.msdoubleointeg";
104
- String channelName = "DoubleO Background Service";
105
- NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
106
- chan.setLightColor(Color.BLUE);
107
- chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
108
- NotificationManager manager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
109
- assert manager != null;
110
- manager.createNotificationChannel(chan);
111
-
112
- Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
113
- NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
114
- Notification notification = notificationBuilder.setOngoing(true)
115
- .setContentTitle(getResources().getString(app_name_id)+" is running")
116
- .setSmallIcon(imageResource)
117
- .setColor(getResources().getColor(notification_color_id))
118
- .setPriority(NotificationManager.IMPORTANCE_MIN)
119
- .setCategory(Notification.CATEGORY_SERVICE)
120
- .setChannelId(NOTIFICATION_CHANNEL_ID)
121
- .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
122
- .setSound(uri)
123
- .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
124
- .build();
125
- startForeground(2, notification);
126
- } else {
127
- Notification notification = new NotificationCompat.Builder(this)
128
- .setContentTitle(getResources().getString(app_name_id)+" is running")
129
- .setSmallIcon(imageResource)
130
- .setColor(getResources().getColor(notification_color_id))
131
- .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
132
- .setCategory(Notification.CATEGORY_SERVICE)
133
- .setOngoing(true)
134
- .build();
135
-
136
- startForeground(1, notification);
137
- }
138
- TimerTask setQueueIntervalObj, setTimerIntervelObj;
139
- Intent serviceIntent = new Intent(getApplicationContext(), mInterfaceReceiver.class);
140
- serviceIntent.setAction("com.example.checkservice");
141
- final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
142
- serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
143
- long firstMillis = System.currentTimeMillis();
144
- AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
145
- alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
146
- 300000, pIntent);
147
-
148
- setQueueToServerInterval = new Timer();
149
- setQueueIntervalObj = new TimerTask() {
150
- public void run() {
151
- if (isConnected()) {
152
- new DespatchQueueMoveToServer().execute();
153
- }
154
- }
155
- };
156
- setQueueToServerInterval.schedule(setQueueIntervalObj, 2000, 2000);
157
-
158
- // App State Info Process //
159
- mInterfaceUtil.validateAppStateInfo(getApplicationContext());
160
-
161
- // **** TimeReader Interval Timer ***** //
162
- setTimerIntervel = new Timer();
163
- setTimerIntervelObj = new TimerTask() {
164
- public void run() {
165
- try {
166
- timeReader();
167
- } catch (Exception e) {
168
- e.printStackTrace();
169
- }
170
- }
171
- };
172
- setTimerIntervel.schedule(setTimerIntervelObj, 60000, 60000);
173
- if (!isGooglePlayServicesAvailable()) {
174
- //need to write location log file...
175
- System.out.println("Play services not available..");
176
- }
177
-
178
- String currentLine;
179
- StringBuilder locConfigObj = new StringBuilder();
180
- File baseDirectory = mInterfaceUtil.rootDirectory;
181
- File locConfigFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_configuration.txt");
182
- if (locConfigFile.exists()) {
183
- BufferedReader readerObj = new BufferedReader(new FileReader(locConfigFile));
184
- while ((currentLine = readerObj.readLine()) != null) {
185
- locConfigObj.append(currentLine);
186
- }
187
- readerObj.close();
188
- JSONObject serverDateObj = new JSONObject(decrypt(locConfigObj.toString()));
189
-
190
- File locationCheckFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_check.txt");
191
- StringBuilder locConfigObj1 = new StringBuilder();
192
- if (locationCheckFile.exists()) {
193
- BufferedReader readerObj1 = new BufferedReader(new FileReader(locationCheckFile));
194
- while ((currentLine = readerObj1.readLine()) != null) {
195
- locConfigObj1.append(currentLine);
196
- }
197
- readerObj1.close();
198
- String locationCheckStr = decrypt(locConfigObj1.toString());
199
- if (locationCheckStr.equals("false")) {
200
- TimerTask timerTask = new TimerTask() {
201
- @Override
202
- public void run() {
203
- try {
204
- getPeriodicalLocationUpdates();
205
- update();
206
- } catch (Exception e) {
207
- e.printStackTrace();
208
- }
209
- }
210
- };
211
- setLocationTimeInterval = new Timer();
212
- setLocationTimeInterval.schedule(timerTask, Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")), Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")));
213
- MINIMUM_INTERVAL = Long.parseLong(serverDateObj.optString("location_fetch_interval_in_seconds").toString());
214
- createLocationRequest();
215
- this.mGoogleApiClient = new GoogleApiClient.Builder(this)
216
- .addConnectionCallbacks(this)
217
- .addOnConnectionFailedListener(this)
218
- .addApi(LocationServices.API)
219
- .build();
220
- mGoogleApiClient.connect();
221
- }
222
- }
223
- } else {
224
- System.out.println("There is no location config file...");
225
- }
226
- File existLastKnownLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/" + "LastKnownLocation.txt");
227
- File existMyLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/" + "MyLocation.txt");
228
- if (existLastKnownLocation.exists()) {
229
- existLastKnownLocation.delete();
230
- }
231
- if (existMyLocation.exists()) {
232
- existMyLocation.delete();
233
- }
234
- } catch (Exception e) {
235
- e.printStackTrace();
236
- }
237
- return START_STICKY;
238
- }
239
-
240
- public static void handleAppStateTimer(String status) {
241
- try {
242
- if (status.equalsIgnoreCase("failure")) {
243
- if (!appStateTimerStatus) {
244
- setProcessInterval = new Timer();
245
- setProcessIntervalObj = new TimerTask() {
246
- public void run() {
247
- appStateTimerStatus = true;
248
- mInterfaceUtil.validateAppStateInfo(context);
249
- }
250
- };
251
- setProcessInterval.schedule(setProcessIntervalObj, 60000, 60000);
252
- }
253
- } else {
254
- if (setProcessInterval != null) {
255
- appStateTimerStatus = false;
256
- setProcessInterval.cancel();
257
- setProcessInterval.purge();
258
- }
259
- if (setProcessIntervalObj != null) {
260
- setProcessIntervalObj.cancel();
261
- }
262
- }
263
- } catch (Exception e) {
264
- e.printStackTrace();
265
- }
266
- }
267
-
268
- private boolean isGooglePlayServicesAvailable() {
269
- int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
270
- if (ConnectionResult.SUCCESS == resultCode) {
271
- return true;
272
- } else {
273
- return false;
274
- }
275
- }
276
-
277
- public void createLocationRequest() {
278
- try {
279
- mLocationRequest = new LocationRequest();
280
- mLocationRequest.setInterval(MINIMUM_INTERVAL * 1000);
281
- mLocationRequest.setFastestInterval(MINIMUM_INTERVAL * 1000);
282
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
283
- } catch (Exception e) {
284
- e.printStackTrace();
285
- }
286
- }
287
-
288
- protected void startLocationUpdates() {
289
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
290
- if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
291
-
292
- }
293
- }
294
- PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
295
- }
296
-
297
- @Override
298
- public void onLocationChanged(Location location) {
299
- if (locationUpdateInd == "true") {
300
- locationUpdateInd = "false";
301
- mCurrentLocation = location;
302
- mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
303
- String lat = String.valueOf(mCurrentLocation.getLatitude());
304
- String lng = String.valueOf(mCurrentLocation.getLongitude());
305
- if (!isLocationDuplicate(lat, lng)) {
306
- new UpdateLocation(lat, lng).execute("");
307
- if (isConnected()) {
308
- new SendLocation().execute();
309
- }
310
- }
311
- String string = ("Lat itude : " + lat + "Longitude : " + lng + "\n");
312
- System.out.println(string);
313
- }
314
- }
315
-
316
- private boolean isLocationDuplicate(String lat, String lng) {
317
- BufferedReader readerObj;
318
- StringBuilder locationData;
319
- File baseDirectory;
320
- String currentLine;
321
- String[] lastKnownLocation;
322
- boolean result = false;
323
- try {
324
- baseDirectory = mInterfaceUtil.rootDirectory;
325
- locationData = new StringBuilder();
326
- File lastKnownLocationFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/LastKnownLocation_encrypted.txt");
327
- if (lastKnownLocationFile.exists()) {
328
- readerObj = new BufferedReader(new FileReader(lastKnownLocationFile));
329
- while ((currentLine = readerObj.readLine()) != null) {
330
- locationData.append(decrypt(currentLine));
331
- }
332
- readerObj.close();
333
- lastKnownLocation = locationData.toString().split(",");
334
- if (lastKnownLocation[0].equals(lat) && lastKnownLocation[1].equals(lng)) {
335
- result = true;
336
- } else {
337
- result = false;
338
- }
339
- } else {
340
- result = false;
341
- }
342
- } catch (Exception e) {
343
- e.printStackTrace();
344
- }
345
- return result;
346
- }
347
-
348
- @Override
349
- public void onConnected(@Nullable Bundle bundle) {
350
- if (mGoogleApiClient.isConnected()) {
351
- startLocationUpdates();
352
- }
353
- }
354
-
355
- @Override
356
- public void onConnectionSuspended(int i) {
357
-
358
- }
359
-
360
- @Override
361
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
362
-
363
- }
364
-
365
- private class DespatchQueueMoveToServer extends AsyncTask<String,
366
- Void,
367
- String> {
368
- @Override
369
- protected String doInBackground(String... params) {
370
- String statusIndication = "false";
371
- try {
372
- String clientID, countryCode, userID, clientUrl;
373
- BufferedReader myAccountsFileReader;
374
- StringBuilder myAccountsFileBuilder;
375
- JSONArray accountsList;
376
- JSONObject currentAccount;
377
- String currentLine;
378
- if (new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt").exists()) {
379
- myAccountsFileReader = new BufferedReader(new FileReader(new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt")));
380
- myAccountsFileBuilder = new StringBuilder();
381
- while ((currentLine = myAccountsFileReader.readLine()) != null) {
382
- myAccountsFileBuilder.append(currentLine);
383
- }
384
- myAccountsFileReader.close();
385
- accountsList = new JSONArray(decrypt(myAccountsFileBuilder.toString()));
386
- if (isConnected()) {
387
- for (int index = 0; index < accountsList.length(); index++) {
388
- currentAccount = accountsList.optJSONObject(index);
389
- clientID = currentAccount.optString("client_id").toString();
390
- countryCode = currentAccount.optString("country_code").toString();
391
- userID = currentAccount.optString("user_id").toString();
392
- clientUrl = currentAccount.optString("client_url").toString();
393
- File baseDirectory = mInterfaceUtil.rootDirectory;
394
- File databaseDir = new File(baseDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database");
395
- File processFileDir = new File(mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/process/");
396
- if (databaseDir.exists()) {
397
- String attachmentsPath = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/attachments";
398
- String queuesPath = baseDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/queue";
399
- if (new File(attachmentsPath).exists()) {
400
- File[] attachmentsFiles = new File(attachmentsPath).listFiles();
401
- if (attachmentsFiles != null) {
402
- for (int attachIndex = 0; attachIndex < attachmentsFiles.length; attachIndex++) {
403
- Arrays.sort(attachmentsFiles);
404
- if (attachmentsFiles[attachIndex].length() == 0) {
405
- break;
406
- }
407
- String[] fileName = attachmentsFiles[attachIndex].toString().split("/");
408
- String attachURL = clientUrl + "/common/components/QueueManager/QueueUpload.aspx?file_path=attachments&client_id=" + clientID + "&country_code=" + countryCode + "&user_id=" + userID + "&file_name=" + fileName[fileName.length - 1].toString();
409
- statusIndication = new mInterfaceUtil().sendFilesToServer(attachmentsFiles[attachIndex].toString(), fileName[fileName.length - 1].toString(), attachURL);
410
- if (statusIndication.equals("true")) {
411
- break;
412
- }
413
- }
414
- }
415
- }
416
- if (statusIndication.equals("false")) {
417
- if (new File(queuesPath).exists()) {
418
- File[] queueFiles = new File(queuesPath).listFiles();
419
- if (queueFiles != null) {
420
- for (int queueIndex = 0; queueIndex < queueFiles.length; queueIndex++) {
421
- Arrays.sort(queueFiles);
422
- if (queueFiles[queueIndex].length() == 0) {
423
- break;
424
- }
425
- String[] fileName = queueFiles[queueIndex].toString().split("/");
426
- String queueURL = clientUrl + "/common/components/QueueManager/QueueUpload.aspx?file_path=queue&client_id=" + clientID + "&country_code=" + countryCode + "&user_id=" + userID + "&file_name=" + fileName[fileName.length - 1].toString();
427
- new mInterfaceUtil().sendFilesToServer(queueFiles[queueIndex].toString(), fileName[fileName.length - 1].toString(), queueURL);
428
- }
429
- }
430
- }
431
- }
432
- } else {
433
- System.out.println("No database directory");
434
- }
435
- }
436
- } else {
437
- System.out.println("No internet connection..");
438
- }
439
- } else {
440
- System.out.println("No my accounts file");
441
- }
442
- } catch (Exception e) {
443
- System.out.println("out exception : " + e.getMessage());
444
- }
445
- return null;
446
- }
447
-
448
- @Override
449
- protected void onPostExecute(String result) {
450
- //Here you are done with the task
451
- System.out.println("Finished...");
452
- }
453
- }
454
-
455
- private void getPeriodicalLocationUpdates() throws Exception {
456
- locationUpdateInd = "true";
457
- mInterfaceUtil.timerInd = "running";
458
- if (mGoogleApiClient.isConnected()) {
459
- startLocationUpdates();
460
- }
461
- }
462
-
463
- private void timeReader() throws Exception {
464
- File baseDirectory = mInterfaceUtil.rootDirectory;
465
- File exist_time_profile = new File(baseDirectory, mInterfaceUtil.packageName + "/time_profile.txt");
466
- if (exist_time_profile.exists()) {
467
- exist_time_profile.delete();
468
- }
469
- String serverTimeObj;
470
- SimpleDateFormat simpleDateFormat;
471
- StringBuilder timeObj;
472
- String currentLine;
473
- BufferedReader readerObj;
474
- JSONObject serverDateObj;
475
- timeObj = new StringBuilder();
476
- BufferedWriter writerObj;
477
- readerObj = new BufferedReader(new FileReader(new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "time_profile_encrypted.txt")));
478
- while ((currentLine = readerObj.readLine()) != null) {
479
- timeObj.append(currentLine);
480
- }
481
- readerObj.close();
482
- serverDateObj = new JSONObject(decrypt(timeObj.toString()));
483
- serverTimeObj = serverDateObj.optString("serverDate").toString();
484
-
485
- // ******SERVER TIME ******//
486
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss", new mInterfaceUtil().locale);
487
- //String currentDateandTime = sdf.format(new Date());
488
- simpleDateFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss", new mInterfaceUtil().locale);
489
- Date date = simpleDateFormat.parse(serverTimeObj);
490
- long a = date.getTime() + 60000;
491
- date.setTime(a);
492
- serverTimeObj = simpleDateFormat.format(date);
493
- serverDateObj.put("serverDate", serverTimeObj);
494
- writerObj = new BufferedWriter(new FileWriter(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "time_profile_encrypted.txt")));
495
- writerObj.write(mInterfaceUtil.encrypt(serverDateObj.toString()));
496
- writerObj.flush();
497
- writerObj.close();
498
- }
499
-
500
- @RequiresApi(api = Build.VERSION_CODES.O)
501
- private class SendLocation extends AsyncTask<String,
502
- Void,
503
- String> {
504
- @Override
505
- protected String doInBackground(String... urls) {
506
- String currentLine, sessionID, localeID, clientID, countryCode, userID, cvsUrl, clientUrl, deviceID, employeeID;
507
- BufferedReader myAccountsFileReader, responseReaderObj;
508
- StringBuilder myAccountsFileBuilder;
509
- JSONArray accountsList;
510
- JSONObject currentAccount, responseDataObj;
511
- StringBuilder locationData,
512
- userData;
513
- BufferedReader readerObj;
514
- BufferedWriter writerObj;
515
- String serverData,
516
- requesturl;
517
- DocumentBuilderFactory dbfObj;
518
- DocumentBuilder dbObj;
519
- Document docObj;
520
- OutputStreamWriter oStreamObj;
521
-
522
-
523
- JSONObject userObj;
524
- HttpURLConnection urlConObj;
525
- URL requestPath;
526
- String str = "";
527
-
528
- try {
529
- File baseDirectory = mInterfaceUtil.rootDirectory;
530
- if (new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt").exists()) {
531
- myAccountsFileReader = new BufferedReader(new FileReader(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt")));
532
- myAccountsFileBuilder = new StringBuilder();
533
- while ((currentLine = myAccountsFileReader.readLine()) != null) {
534
- myAccountsFileBuilder.append(currentLine);
535
- }
536
- myAccountsFileReader.close();
537
- accountsList = new JSONArray(decrypt(myAccountsFileBuilder.toString()));
538
- locationData = new StringBuilder();
539
- readerObj = new BufferedReader(new FileReader(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/MyLocation_encrypted.txt")));
540
- while ((currentLine = readerObj.readLine()) != null) {
541
- locationData.append(decrypt(currentLine));
542
- //lastKnownLocation = currentLine + "\n";
543
- }
544
- readerObj.close();
545
- serverData = locationData.toString();
546
-
547
- /* CLEARING THE LOCATION POINTS */
548
- if (serverData != "") {
549
- writerObj = new BufferedWriter(new FileWriter(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/MyLocation_encrypted.txt")));
550
- writerObj.write("");
551
- writerObj.flush();
552
- writerObj.close();
553
- }
554
-
555
- for (int index = 0; index < accountsList.length(); index++) {
556
- currentAccount = accountsList.optJSONObject(index);
557
- if (currentAccount.optString("location_update_ind").toString().equals("true")) {
558
- sessionID = mInterfaceUtil.sessionID;
559
- localeID = mInterfaceUtil.localeID;
560
- clientID = mInterfaceUtil.clientID;
561
- countryCode = mInterfaceUtil.countryCode;
562
- userID = mInterfaceUtil.userID;
563
- employeeID = mInterfaceUtil.employeeId;
564
- cvsUrl = mInterfaceUtil.cvsUrl;
565
- clientUrl = mInterfaceUtil.clientUrl;
566
- deviceID = mInterfaceUtil.deviceID;
567
-
568
- requesturl = clientUrl + "/common/components/GeoLocation/update_device_location_offline.aspx";
569
-
570
- /* SEND LOCATION */
571
- requestPath = new URL(requesturl);
572
- urlConObj = (HttpURLConnection) requestPath.openConnection();
573
- urlConObj.setDoOutput(true);
574
- urlConObj.setRequestMethod("POST");
575
- urlConObj.setRequestProperty("CONTENT-TYPE", "text/xml");
576
- urlConObj.connect();
577
- oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
578
- oStreamObj.write("<location_xml><client_id>" + clientID + "</client_id><country_code>" + countryCode + "</country_code><device_id>" + deviceID + "</device_id><location>" + serverData + "</location></location_xml>");
579
- oStreamObj.flush();
580
- oStreamObj.close();
581
- urlConObj.getResponseCode();
582
- urlConObj.disconnect();
583
- } else {
584
- System.out.println("Location should not be updated for this user..");
585
- }
586
- }
587
- }
588
- } catch (Exception ex) {
589
- ex.printStackTrace();
590
- }
591
- return null;
592
- }
593
- }
594
-
595
- private class UpdateLocation extends AsyncTask<String,
596
- Void,
597
- String> {
598
- private String objLat,
599
- objLon;
600
-
601
- public UpdateLocation(String lat, String lon) {
602
- this.objLat = lat;
603
- this.objLon = lon;
604
- }
605
-
606
- @Override
607
- protected String doInBackground(String... urls) {
608
- File appDirectory,
609
- baseDirectory = mInterfaceUtil.rootDirectory;
610
- FileWriter fileWriterObj;
611
- appDirectory = new File(baseDirectory + "/" + mInterfaceUtil.packageName);
612
- if (appDirectory.exists()) {
613
- try {
614
- fileWriterObj = new FileWriter(new File(baseDirectory, mInterfaceUtil.packageName + "/MyLocation_encrypted.txt"), true);
615
- fileWriterObj.write(mInterfaceUtil.encrypt(this.objLat + "," + this.objLon + "," + new SimpleDateFormat("yyyyMMddHHmmss", new mInterfaceUtil().locale).format(new Date()) + "\n"));
616
- fileWriterObj.flush();
617
- fileWriterObj.close();
618
-
619
- fileWriterObj = new FileWriter(new File(baseDirectory, mInterfaceUtil.packageName + "/LastKnownLocation_encrypted.txt"), false);
620
- fileWriterObj.write(mInterfaceUtil.encrypt(this.objLat + "," + this.objLon + "," + new SimpleDateFormat("yyyyMMddHHmmss", new mInterfaceUtil().locale).format(new Date())));
621
- fileWriterObj.flush();
622
- fileWriterObj.close();
623
- File existLastKnownLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/LastKnownLocation.txt");
624
- File existMyLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/MyLocation.txt");
625
- if (existLastKnownLocation.exists()) {
626
- existLastKnownLocation.delete();
627
- }
628
- if (existMyLocation.exists()) {
629
- existMyLocation.delete();
630
- }
631
- } catch (Exception e) {
632
- e.printStackTrace();
633
- }
634
- }
635
- return null;
636
- }
637
- }
638
-
639
-
640
- /* USER CLEARED APP FROM CACHE */
641
- @Override
642
- public void onTaskRemoved(Intent rootIntent) {
643
- super.onTaskRemoved(rootIntent);
644
-
645
- if (setQueueInterval != null) {
646
- setQueueInterval.cancel();
647
- }
648
- if (setTimerIntervel != null) {
649
- setTimerIntervel.cancel();
650
- }
651
- Intent restartService = new Intent(getApplicationContext(),
652
- this.getClass());
653
- restartService.setPackage(getPackageName());
654
- PendingIntent restartServicePI = PendingIntent.getService(
655
- getApplicationContext(), 1, restartService,
656
- PendingIntent.FLAG_ONE_SHOT);
657
- AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
658
- alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
659
- }
660
-
661
- /* WHEN THE RAM IS LOW */
662
- @Override
663
- public void onLowMemory() {
664
- super.onLowMemory();
665
-
666
- if (setQueueInterval != null) {
667
- setQueueInterval.cancel();
668
- }
669
-
670
- if (setTimerIntervel != null) {
671
- setTimerIntervel.cancel();
672
- }
673
-
674
- startService(new Intent(getApplicationContext(), mInterfaceService.class));
675
- }
676
-
677
- /* USER CLICK FORCE STOP IN SETTINGS */
678
- @Override
679
- public void onDestroy() {
680
- super.onDestroy();
681
-
682
- if (setQueueInterval != null) {
683
- setQueueInterval.cancel();
684
- }
685
-
686
- if (setTimerIntervel != null) {
687
- setTimerIntervel.cancel();
688
- }
689
- startService(new Intent(getApplicationContext(), mInterfaceService.class));
690
- }
691
-
692
- public boolean isConnected() {
693
- ConnectivityManager online = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
694
- NetworkInfo networkInfo = online.getActiveNetworkInfo();
695
- if (networkInfo != null && networkInfo.isConnected()) {
696
- return true;
697
- } else {
698
- return false;
699
- }
700
- }
701
-
702
- public class CoresTimerTask extends TimerTask {
703
- private boolean hasStarted = false;
704
-
705
- public void run() {
706
- this.hasStarted = true;
707
- setLocationTimeInterval = new Timer();
708
- try {
709
- getPeriodicalLocationUpdates();
710
- } catch (Exception e) {
711
- e.printStackTrace();
712
- }
713
- }
714
-
715
- public boolean hasRunStarted() {
716
- return this.hasStarted;
717
- }
718
- }
719
-
720
- public void update() throws IOException, JSONException {
721
- TimerTask timerTask = new TimerTask() {
722
- @Override
723
- public void run() {
724
- System.out.println("Updated timer");
725
- try {
726
- getPeriodicalLocationUpdates();
727
- } catch (Exception e) {
728
- e.printStackTrace();
729
- }
730
- }
731
- };
732
- String currentLine;
733
- StringBuilder locConfigObj = new StringBuilder();
734
- File baseDirectory = mInterfaceUtil.rootDirectory;
735
- File locConfigFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_configuration.txt");
736
- if (locConfigFile.exists()) {
737
- BufferedReader readerObj = new BufferedReader(new FileReader(locConfigFile));
738
- while ((currentLine = readerObj.readLine()) != null) {
739
- locConfigObj.append(currentLine);
740
- }
741
- readerObj.close();
742
- JSONObject serverDateObj = new JSONObject(decrypt(locConfigObj.toString()));
743
- setLocationTimeInterval.cancel();
744
- setLocationTimeInterval = new Timer();
745
- setLocationTimeInterval.schedule(timerTask, Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")), Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")));
746
- }
747
- }
748
-
749
- }
1
+ package com.selfservit.util;
2
+
3
+ import android.Manifest;
4
+ import android.annotation.TargetApi;
5
+ import android.app.AlarmManager;
6
+ import android.app.Notification;
7
+ import android.app.NotificationChannel;
8
+ import android.app.NotificationManager;
9
+ import android.app.PendingIntent;
10
+ import android.app.Service;
11
+ import android.content.Context;
12
+ import android.content.Intent;
13
+ import android.content.pm.PackageManager;
14
+ import android.graphics.Color;
15
+ import android.location.Location;
16
+ import android.media.RingtoneManager;
17
+ import android.net.ConnectivityManager;
18
+ import android.net.NetworkInfo;
19
+ import android.net.Uri;
20
+ import android.os.AsyncTask;
21
+ import android.os.Build;
22
+ import android.os.Bundle;
23
+ import android.os.Environment;
24
+ import android.os.IBinder;
25
+ import android.os.SystemClock;
26
+ import android.support.annotation.NonNull;
27
+ import android.support.annotation.Nullable;
28
+ import android.support.annotation.RequiresApi;
29
+ import android.support.v4.app.NotificationCompat;
30
+
31
+ import com.google.android.gms.common.ConnectionResult;
32
+ import com.google.android.gms.common.GooglePlayServicesUtil;
33
+ import com.google.android.gms.common.api.GoogleApiClient;
34
+ import com.google.android.gms.common.api.PendingResult;
35
+ import com.google.android.gms.common.api.Status;
36
+ import com.google.android.gms.location.LocationRequest;
37
+ import com.google.android.gms.location.LocationServices;
38
+
39
+ import org.json.JSONArray;
40
+ import org.json.JSONException;
41
+ import org.json.JSONObject;
42
+ import org.w3c.dom.Document;
43
+
44
+ import java.io.BufferedReader;
45
+ import java.io.BufferedWriter;
46
+ import java.io.File;
47
+ import java.io.FileReader;
48
+ import java.io.FileWriter;
49
+ import java.io.IOException;
50
+ import java.io.OutputStreamWriter;
51
+ import java.net.HttpURLConnection;
52
+ import java.net.URL;
53
+ import java.text.DateFormat;
54
+ import java.text.SimpleDateFormat;
55
+ import java.util.Arrays;
56
+ import java.util.Date;
57
+ import java.util.Timer;
58
+ import java.util.TimerTask;
59
+
60
+ import javax.xml.parsers.DocumentBuilder;
61
+ import javax.xml.parsers.DocumentBuilderFactory;
62
+
63
+ import static com.selfservit.util.mInterfaceUtil.decrypt;
64
+
65
+ @TargetApi(Build.VERSION_CODES.O)
66
+ public class mInterfaceService extends Service implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
67
+ public Timer setQueueInterval,
68
+ setQueueToServerInterval,
69
+ setTimerIntervel,
70
+ setLocationTimeInterval;
71
+ GoogleApiClient mGoogleApiClient;
72
+ LocationRequest mLocationRequest;
73
+ Location mCurrentLocation;
74
+ String mLastUpdateTime;
75
+ private static long MINIMUM_INTERVAL = 0;
76
+ private static TimerTask setProcessIntervalObj;
77
+ private static Timer setProcessInterval;
78
+ private static Context context;
79
+ public static boolean appStateTimerStatus = false;
80
+ String notification_icon, notification_color, app_name;
81
+ int imageResource, app_name_id, notification_color_id;
82
+ String locationUpdateInd = "false";
83
+ @ Override
84
+ public IBinder onBind(Intent intent) {
85
+ // TODO: Return the communication channel to the service.
86
+ throw new UnsupportedOperationException("Not yet implemented");
87
+ }
88
+ @ Override
89
+ @TargetApi(Build.VERSION_CODES.O)
90
+ public int onStartCommand(Intent intent, int flags, int startId) {
91
+ try {
92
+ this.context = getApplicationContext();
93
+ if (mInterfaceUtil.packageName.equals("")) {
94
+ mInterfaceUtil.packageName = getApplicationContext().getPackageName().split("\\.")[2];
95
+ }
96
+ notification_icon = "@drawable/ic_notification";
97
+ notification_color = "@color/notification_accent";
98
+ app_name = "@string/app_name";
99
+ imageResource = getResources().getIdentifier(notification_icon, null, getPackageName());
100
+ app_name_id = getResources().getIdentifier(app_name, null, getPackageName());
101
+ notification_color_id = getResources().getIdentifier(notification_color, null, getPackageName());
102
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
103
+ String NOTIFICATION_CHANNEL_ID = "com.selfservit.msdoubleointeg";
104
+ String channelName = "DoubleO Background Service";
105
+ NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
106
+ chan.setLightColor(Color.BLUE);
107
+ chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
108
+ NotificationManager manager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
109
+ assert manager != null;
110
+ manager.createNotificationChannel(chan);
111
+
112
+ Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
113
+ NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
114
+ Notification notification = notificationBuilder.setOngoing(true)
115
+ .setContentTitle(getResources().getString(app_name_id)+" is running")
116
+ .setSmallIcon(imageResource)
117
+ .setColor(getResources().getColor(notification_color_id))
118
+ .setPriority(NotificationManager.IMPORTANCE_MIN)
119
+ .setCategory(Notification.CATEGORY_SERVICE)
120
+ .setChannelId(NOTIFICATION_CHANNEL_ID)
121
+ .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
122
+ .setSound(uri)
123
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
124
+ .build();
125
+ startForeground(2, notification);
126
+ } else {
127
+ Notification notification = new NotificationCompat.Builder(this)
128
+ .setContentTitle(getResources().getString(app_name_id)+" is running")
129
+ .setSmallIcon(imageResource)
130
+ .setColor(getResources().getColor(notification_color_id))
131
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
132
+ .setCategory(Notification.CATEGORY_SERVICE)
133
+ .setOngoing(true)
134
+ .build();
135
+
136
+ startForeground(1, notification);
137
+ }
138
+ TimerTask setQueueIntervalObj, setTimerIntervelObj;
139
+ Intent serviceIntent = new Intent(getApplicationContext(), mInterfaceReceiver.class);
140
+ serviceIntent.setAction("com.example.checkservice");
141
+ final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
142
+ serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
143
+ long firstMillis = System.currentTimeMillis();
144
+ AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
145
+ alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
146
+ 300000, pIntent);
147
+
148
+ setQueueToServerInterval = new Timer();
149
+ setQueueIntervalObj = new TimerTask() {
150
+ public void run() {
151
+ if (isConnected()) {
152
+ new DespatchQueueMoveToServer().execute();
153
+ }
154
+ }
155
+ };
156
+ setQueueToServerInterval.schedule(setQueueIntervalObj, 2000, 2000);
157
+
158
+ // App State Info Process //
159
+ mInterfaceUtil.validateAppStateInfo(getApplicationContext());
160
+
161
+ // **** TimeReader Interval Timer ***** //
162
+ setTimerIntervel = new Timer();
163
+ setTimerIntervelObj = new TimerTask() {
164
+ public void run() {
165
+ try {
166
+ timeReader();
167
+ } catch (Exception e) {
168
+ e.printStackTrace();
169
+ }
170
+ }
171
+ };
172
+ setTimerIntervel.schedule(setTimerIntervelObj, 60000, 60000);
173
+ if (!isGooglePlayServicesAvailable()) {
174
+ //need to write location log file...
175
+ System.out.println("Play services not available..");
176
+ }
177
+
178
+ String currentLine;
179
+ StringBuilder locConfigObj = new StringBuilder();
180
+ File baseDirectory = mInterfaceUtil.rootDirectory;
181
+ File locConfigFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_configuration.txt");
182
+ if (locConfigFile.exists()) {
183
+ BufferedReader readerObj = new BufferedReader(new FileReader(locConfigFile));
184
+ while ((currentLine = readerObj.readLine()) != null) {
185
+ locConfigObj.append(currentLine);
186
+ }
187
+ readerObj.close();
188
+ JSONObject serverDateObj = new JSONObject(decrypt(locConfigObj.toString()));
189
+
190
+ File locationCheckFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_check.txt");
191
+ StringBuilder locConfigObj1 = new StringBuilder();
192
+ if (locationCheckFile.exists()) {
193
+ BufferedReader readerObj1 = new BufferedReader(new FileReader(locationCheckFile));
194
+ while ((currentLine = readerObj1.readLine()) != null) {
195
+ locConfigObj1.append(currentLine);
196
+ }
197
+ readerObj1.close();
198
+ String locationCheckStr = decrypt(locConfigObj1.toString());
199
+ if (locationCheckStr.equals("false")) {
200
+ TimerTask timerTask = new TimerTask() {
201
+ @Override
202
+ public void run() {
203
+ try {
204
+ getPeriodicalLocationUpdates();
205
+ update();
206
+ } catch (Exception e) {
207
+ e.printStackTrace();
208
+ }
209
+ }
210
+ };
211
+ if(setLocationTimeInterval == null){
212
+ setLocationTimeInterval = new Timer();
213
+ setLocationTimeInterval.schedule(timerTask, Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")), Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")));
214
+ MINIMUM_INTERVAL = Long.parseLong(serverDateObj.optString("location_fetch_interval_in_seconds").toString());
215
+ createLocationRequest();
216
+ this.mGoogleApiClient = new GoogleApiClient.Builder(this)
217
+ .addConnectionCallbacks(this)
218
+ .addOnConnectionFailedListener(this)
219
+ .addApi(LocationServices.API)
220
+ .build();
221
+ mGoogleApiClient.connect();
222
+ };
223
+
224
+ }
225
+ }
226
+ } else {
227
+ System.out.println("There is no location config file...");
228
+ }
229
+ File existLastKnownLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/" + "LastKnownLocation.txt");
230
+ File existMyLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/" + "MyLocation.txt");
231
+ if (existLastKnownLocation.exists()) {
232
+ existLastKnownLocation.delete();
233
+ }
234
+ if (existMyLocation.exists()) {
235
+ existMyLocation.delete();
236
+ }
237
+ } catch (Exception e) {
238
+ e.printStackTrace();
239
+ }
240
+ return START_STICKY;
241
+ }
242
+
243
+ public static void handleAppStateTimer(String status) {
244
+ try {
245
+ if (status.equalsIgnoreCase("failure")) {
246
+ if (!appStateTimerStatus) {
247
+ setProcessInterval = new Timer();
248
+ setProcessIntervalObj = new TimerTask() {
249
+ public void run() {
250
+ appStateTimerStatus = true;
251
+ mInterfaceUtil.validateAppStateInfo(context);
252
+ }
253
+ };
254
+ setProcessInterval.schedule(setProcessIntervalObj, 60000, 60000);
255
+ }
256
+ } else {
257
+ if (setProcessInterval != null) {
258
+ appStateTimerStatus = false;
259
+ setProcessInterval.cancel();
260
+ setProcessInterval.purge();
261
+ }
262
+ if (setProcessIntervalObj != null) {
263
+ setProcessIntervalObj.cancel();
264
+ }
265
+ }
266
+ } catch (Exception e) {
267
+ e.printStackTrace();
268
+ }
269
+ }
270
+
271
+ private boolean isGooglePlayServicesAvailable() {
272
+ int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
273
+ if (ConnectionResult.SUCCESS == resultCode) {
274
+ return true;
275
+ } else {
276
+ return false;
277
+ }
278
+ }
279
+
280
+ public void createLocationRequest() {
281
+ try {
282
+ mLocationRequest = new LocationRequest();
283
+ mLocationRequest.setInterval(MINIMUM_INTERVAL * 1000);
284
+ mLocationRequest.setFastestInterval(MINIMUM_INTERVAL * 1000);
285
+ mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
286
+ } catch (Exception e) {
287
+ e.printStackTrace();
288
+ }
289
+ }
290
+
291
+ protected void startLocationUpdates() {
292
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
293
+ if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
294
+
295
+ }
296
+ }
297
+ PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
298
+ }
299
+
300
+ @Override
301
+ public void onLocationChanged(Location location) {
302
+ if (locationUpdateInd == "true") {
303
+ locationUpdateInd = "false";
304
+ mCurrentLocation = location;
305
+ mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
306
+ String lat = String.valueOf(mCurrentLocation.getLatitude());
307
+ String lng = String.valueOf(mCurrentLocation.getLongitude());
308
+ if (!isLocationDuplicate(lat, lng)) {
309
+ new UpdateLocation(lat, lng).execute("");
310
+ if (isConnected()) {
311
+ new SendLocation().execute();
312
+ }
313
+ }
314
+ String string = ("Lat itude : " + lat + "Longitude : " + lng + "\n");
315
+ System.out.println(string);
316
+ }
317
+ }
318
+
319
+ private boolean isLocationDuplicate(String lat, String lng) {
320
+ BufferedReader readerObj;
321
+ StringBuilder locationData;
322
+ File baseDirectory;
323
+ String currentLine;
324
+ String[] lastKnownLocation;
325
+ boolean result = false;
326
+ try {
327
+ baseDirectory = mInterfaceUtil.rootDirectory;
328
+ locationData = new StringBuilder();
329
+ File lastKnownLocationFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/LastKnownLocation_encrypted.txt");
330
+ if (lastKnownLocationFile.exists()) {
331
+ readerObj = new BufferedReader(new FileReader(lastKnownLocationFile));
332
+ while ((currentLine = readerObj.readLine()) != null) {
333
+ locationData.append(decrypt(currentLine));
334
+ }
335
+ readerObj.close();
336
+ lastKnownLocation = locationData.toString().split(",");
337
+ if (lastKnownLocation[0].equals(lat) && lastKnownLocation[1].equals(lng)) {
338
+ result = true;
339
+ } else {
340
+ result = false;
341
+ }
342
+ } else {
343
+ result = false;
344
+ }
345
+ } catch (Exception e) {
346
+ e.printStackTrace();
347
+ }
348
+ return result;
349
+ }
350
+
351
+ @Override
352
+ public void onConnected(@Nullable Bundle bundle) {
353
+ if (mGoogleApiClient.isConnected()) {
354
+ startLocationUpdates();
355
+ }
356
+ }
357
+
358
+ @Override
359
+ public void onConnectionSuspended(int i) {
360
+
361
+ }
362
+
363
+ @Override
364
+ public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
365
+
366
+ }
367
+
368
+ private class DespatchQueueMoveToServer extends AsyncTask<String,
369
+ Void,
370
+ String> {
371
+ @Override
372
+ protected String doInBackground(String... params) {
373
+ String statusIndication = "false";
374
+ try {
375
+ String clientID, countryCode, userID, clientUrl;
376
+ BufferedReader myAccountsFileReader;
377
+ StringBuilder myAccountsFileBuilder;
378
+ JSONArray accountsList;
379
+ JSONObject currentAccount;
380
+ String currentLine;
381
+ if (new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt").exists()) {
382
+ myAccountsFileReader = new BufferedReader(new FileReader(new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt")));
383
+ myAccountsFileBuilder = new StringBuilder();
384
+ while ((currentLine = myAccountsFileReader.readLine()) != null) {
385
+ myAccountsFileBuilder.append(currentLine);
386
+ }
387
+ myAccountsFileReader.close();
388
+ accountsList = new JSONArray(decrypt(myAccountsFileBuilder.toString()));
389
+ if (isConnected()) {
390
+ for (int index = 0; index < accountsList.length(); index++) {
391
+ currentAccount = accountsList.optJSONObject(index);
392
+ clientID = currentAccount.optString("client_id").toString();
393
+ countryCode = currentAccount.optString("country_code").toString();
394
+ userID = currentAccount.optString("user_id").toString();
395
+ clientUrl = currentAccount.optString("client_url").toString();
396
+ File baseDirectory = mInterfaceUtil.rootDirectory;
397
+ File databaseDir = new File(baseDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database");
398
+ File processFileDir = new File(mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/process/");
399
+ if (databaseDir.exists()) {
400
+ String attachmentsPath = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/attachments";
401
+ String queuesPath = baseDirectory + "/" + mInterfaceUtil.packageName + "/" + clientID + "/" + countryCode + "/database/queue";
402
+ if (new File(attachmentsPath).exists()) {
403
+ File[] attachmentsFiles = new File(attachmentsPath).listFiles();
404
+ if (attachmentsFiles != null) {
405
+ for (int attachIndex = 0; attachIndex < attachmentsFiles.length; attachIndex++) {
406
+ Arrays.sort(attachmentsFiles);
407
+ if (attachmentsFiles[attachIndex].length() == 0) {
408
+ break;
409
+ }
410
+ String[] fileName = attachmentsFiles[attachIndex].toString().split("/");
411
+ String attachURL = clientUrl + "/common/components/QueueManager/QueueUpload.aspx?file_path=attachments&client_id=" + clientID + "&country_code=" + countryCode + "&user_id=" + userID + "&file_name=" + fileName[fileName.length - 1].toString();
412
+ statusIndication = new mInterfaceUtil().sendFilesToServer(attachmentsFiles[attachIndex].toString(), fileName[fileName.length - 1].toString(), attachURL);
413
+ if (statusIndication.equals("true")) {
414
+ break;
415
+ }
416
+ }
417
+ }
418
+ }
419
+ if (statusIndication.equals("false")) {
420
+ if (new File(queuesPath).exists()) {
421
+ File[] queueFiles = new File(queuesPath).listFiles();
422
+ if (queueFiles != null) {
423
+ for (int queueIndex = 0; queueIndex < queueFiles.length; queueIndex++) {
424
+ Arrays.sort(queueFiles);
425
+ if (queueFiles[queueIndex].length() == 0) {
426
+ break;
427
+ }
428
+ String[] fileName = queueFiles[queueIndex].toString().split("/");
429
+ String queueURL = clientUrl + "/common/components/QueueManager/QueueUpload.aspx?file_path=queue&client_id=" + clientID + "&country_code=" + countryCode + "&user_id=" + userID + "&file_name=" + fileName[fileName.length - 1].toString();
430
+ new mInterfaceUtil().sendFilesToServer(queueFiles[queueIndex].toString(), fileName[fileName.length - 1].toString(), queueURL);
431
+ }
432
+ }
433
+ }
434
+ }
435
+ } else {
436
+ System.out.println("No database directory");
437
+ }
438
+ }
439
+ } else {
440
+ System.out.println("No internet connection..");
441
+ }
442
+ } else {
443
+ System.out.println("No my accounts file");
444
+ }
445
+ } catch (Exception e) {
446
+ System.out.println("out exception : " + e.getMessage());
447
+ }
448
+ return null;
449
+ }
450
+
451
+ @Override
452
+ protected void onPostExecute(String result) {
453
+ //Here you are done with the task
454
+ System.out.println("Finished...");
455
+ }
456
+ }
457
+
458
+ private void getPeriodicalLocationUpdates() throws Exception {
459
+ locationUpdateInd = "true";
460
+ mInterfaceUtil.timerInd = "running";
461
+ if (mGoogleApiClient.isConnected()) {
462
+ startLocationUpdates();
463
+ }
464
+ }
465
+
466
+ private void timeReader() throws Exception {
467
+ File baseDirectory = mInterfaceUtil.rootDirectory;
468
+ File exist_time_profile = new File(baseDirectory, mInterfaceUtil.packageName + "/time_profile.txt");
469
+ if (exist_time_profile.exists()) {
470
+ exist_time_profile.delete();
471
+ }
472
+ String serverTimeObj;
473
+ SimpleDateFormat simpleDateFormat;
474
+ StringBuilder timeObj;
475
+ String currentLine;
476
+ BufferedReader readerObj;
477
+ JSONObject serverDateObj;
478
+ timeObj = new StringBuilder();
479
+ BufferedWriter writerObj;
480
+ readerObj = new BufferedReader(new FileReader(new File(mInterfaceUtil.rootDirectory, "/" + mInterfaceUtil.packageName + "/" + "time_profile_encrypted.txt")));
481
+ while ((currentLine = readerObj.readLine()) != null) {
482
+ timeObj.append(currentLine);
483
+ }
484
+ readerObj.close();
485
+ serverDateObj = new JSONObject(decrypt(timeObj.toString()));
486
+ serverTimeObj = serverDateObj.optString("serverDate").toString();
487
+
488
+ // ******SERVER TIME ******//
489
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss", new mInterfaceUtil().locale);
490
+ //String currentDateandTime = sdf.format(new Date());
491
+ simpleDateFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss", new mInterfaceUtil().locale);
492
+ Date date = simpleDateFormat.parse(serverTimeObj);
493
+ long a = date.getTime() + 60000;
494
+ date.setTime(a);
495
+ serverTimeObj = simpleDateFormat.format(date);
496
+ serverDateObj.put("serverDate", serverTimeObj);
497
+ writerObj = new BufferedWriter(new FileWriter(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "time_profile_encrypted.txt")));
498
+ writerObj.write(mInterfaceUtil.encrypt(serverDateObj.toString()));
499
+ writerObj.flush();
500
+ writerObj.close();
501
+ }
502
+
503
+ @RequiresApi(api = Build.VERSION_CODES.O)
504
+ private class SendLocation extends AsyncTask<String,
505
+ Void,
506
+ String> {
507
+ @Override
508
+ protected String doInBackground(String... urls) {
509
+ String currentLine, sessionID, localeID, clientID, countryCode, userID, cvsUrl, clientUrl, deviceID, employeeID;
510
+ BufferedReader myAccountsFileReader, responseReaderObj;
511
+ StringBuilder myAccountsFileBuilder;
512
+ JSONArray accountsList;
513
+ JSONObject currentAccount, responseDataObj;
514
+ StringBuilder locationData,
515
+ userData;
516
+ BufferedReader readerObj;
517
+ BufferedWriter writerObj;
518
+ String serverData,
519
+ requesturl;
520
+ DocumentBuilderFactory dbfObj;
521
+ DocumentBuilder dbObj;
522
+ Document docObj;
523
+ OutputStreamWriter oStreamObj;
524
+
525
+
526
+ JSONObject userObj;
527
+ HttpURLConnection urlConObj;
528
+ URL requestPath;
529
+ String str = "";
530
+
531
+ try {
532
+ File baseDirectory = mInterfaceUtil.rootDirectory;
533
+ if (new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt").exists()) {
534
+ myAccountsFileReader = new BufferedReader(new FileReader(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/" + "my_accounts_encrypted.txt")));
535
+ myAccountsFileBuilder = new StringBuilder();
536
+ while ((currentLine = myAccountsFileReader.readLine()) != null) {
537
+ myAccountsFileBuilder.append(currentLine);
538
+ }
539
+ myAccountsFileReader.close();
540
+ accountsList = new JSONArray(decrypt(myAccountsFileBuilder.toString()));
541
+ locationData = new StringBuilder();
542
+ readerObj = new BufferedReader(new FileReader(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/MyLocation_encrypted.txt")));
543
+ while ((currentLine = readerObj.readLine()) != null) {
544
+ locationData.append(decrypt(currentLine));
545
+ //lastKnownLocation = currentLine + "\n";
546
+ }
547
+ readerObj.close();
548
+ serverData = locationData.toString();
549
+
550
+ /* CLEARING THE LOCATION POINTS */
551
+ if (serverData != "") {
552
+ writerObj = new BufferedWriter(new FileWriter(new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/MyLocation_encrypted.txt")));
553
+ writerObj.write("");
554
+ writerObj.flush();
555
+ writerObj.close();
556
+ }
557
+
558
+ for (int index = 0; index < accountsList.length(); index++) {
559
+ currentAccount = accountsList.optJSONObject(index);
560
+ if (currentAccount.optString("location_update_ind").toString().equals("true")) {
561
+ sessionID = mInterfaceUtil.sessionID;
562
+ localeID = mInterfaceUtil.localeID;
563
+ clientID = mInterfaceUtil.clientID;
564
+ countryCode = mInterfaceUtil.countryCode;
565
+ userID = mInterfaceUtil.userID;
566
+ employeeID = mInterfaceUtil.employeeId;
567
+ cvsUrl = mInterfaceUtil.cvsUrl;
568
+ clientUrl = mInterfaceUtil.clientUrl;
569
+ deviceID = mInterfaceUtil.deviceID;
570
+
571
+ requesturl = clientUrl + "/common/components/GeoLocation/update_device_location_offline.aspx";
572
+
573
+ /* SEND LOCATION */
574
+ requestPath = new URL(requesturl);
575
+ urlConObj = (HttpURLConnection) requestPath.openConnection();
576
+ urlConObj.setDoOutput(true);
577
+ urlConObj.setRequestMethod("POST");
578
+ urlConObj.setRequestProperty("CONTENT-TYPE", "text/xml");
579
+ urlConObj.connect();
580
+ oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
581
+ oStreamObj.write("<location_xml><client_id>" + clientID + "</client_id><country_code>" + countryCode + "</country_code><device_id>" + deviceID + "</device_id><location>" + serverData + "</location></location_xml>");
582
+ oStreamObj.flush();
583
+ oStreamObj.close();
584
+ urlConObj.getResponseCode();
585
+ urlConObj.disconnect();
586
+ } else {
587
+ System.out.println("Location should not be updated for this user..");
588
+ }
589
+ }
590
+ }
591
+ } catch (Exception ex) {
592
+ ex.printStackTrace();
593
+ }
594
+ return null;
595
+ }
596
+ }
597
+
598
+ private class UpdateLocation extends AsyncTask<String,
599
+ Void,
600
+ String> {
601
+ private String objLat,
602
+ objLon;
603
+
604
+ public UpdateLocation(String lat, String lon) {
605
+ this.objLat = lat;
606
+ this.objLon = lon;
607
+ }
608
+
609
+ @Override
610
+ protected String doInBackground(String... urls) {
611
+ File appDirectory,
612
+ baseDirectory = mInterfaceUtil.rootDirectory;
613
+ FileWriter fileWriterObj;
614
+ appDirectory = new File(baseDirectory + "/" + mInterfaceUtil.packageName);
615
+ if (appDirectory.exists()) {
616
+ try {
617
+ fileWriterObj = new FileWriter(new File(baseDirectory, mInterfaceUtil.packageName + "/MyLocation_encrypted.txt"), true);
618
+ fileWriterObj.write(mInterfaceUtil.encrypt(this.objLat + "," + this.objLon + "," + new SimpleDateFormat("yyyyMMddHHmmss", new mInterfaceUtil().locale).format(new Date()) + "\n"));
619
+ fileWriterObj.flush();
620
+ fileWriterObj.close();
621
+
622
+ fileWriterObj = new FileWriter(new File(baseDirectory, mInterfaceUtil.packageName + "/LastKnownLocation_encrypted.txt"), false);
623
+ fileWriterObj.write(mInterfaceUtil.encrypt(this.objLat + "," + this.objLon + "," + new SimpleDateFormat("yyyyMMddHHmmss", new mInterfaceUtil().locale).format(new Date())));
624
+ fileWriterObj.flush();
625
+ fileWriterObj.close();
626
+ File existLastKnownLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/LastKnownLocation.txt");
627
+ File existMyLocation = new File(baseDirectory, mInterfaceUtil.packageName + "/MyLocation.txt");
628
+ if (existLastKnownLocation.exists()) {
629
+ existLastKnownLocation.delete();
630
+ }
631
+ if (existMyLocation.exists()) {
632
+ existMyLocation.delete();
633
+ }
634
+ } catch (Exception e) {
635
+ e.printStackTrace();
636
+ }
637
+ }
638
+ return null;
639
+ }
640
+ }
641
+
642
+
643
+ /* USER CLEARED APP FROM CACHE */
644
+ @Override
645
+ public void onTaskRemoved(Intent rootIntent) {
646
+ super.onTaskRemoved(rootIntent);
647
+
648
+ if (setQueueInterval != null) {
649
+ setQueueInterval.cancel();
650
+ }
651
+ if (setTimerIntervel != null) {
652
+ setTimerIntervel.cancel();
653
+ }
654
+ Intent restartService = new Intent(getApplicationContext(),
655
+ this.getClass());
656
+ restartService.setPackage(getPackageName());
657
+ PendingIntent restartServicePI = PendingIntent.getService(
658
+ getApplicationContext(), 1, restartService,
659
+ PendingIntent.FLAG_ONE_SHOT);
660
+ AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
661
+ alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
662
+ }
663
+
664
+ /* WHEN THE RAM IS LOW */
665
+ @Override
666
+ public void onLowMemory() {
667
+ super.onLowMemory();
668
+
669
+ if (setQueueInterval != null) {
670
+ setQueueInterval.cancel();
671
+ }
672
+
673
+ if (setTimerIntervel != null) {
674
+ setTimerIntervel.cancel();
675
+ }
676
+
677
+ startService(new Intent(getApplicationContext(), mInterfaceService.class));
678
+ }
679
+
680
+ /* USER CLICK FORCE STOP IN SETTINGS */
681
+ @Override
682
+ public void onDestroy() {
683
+ super.onDestroy();
684
+
685
+ if (setQueueInterval != null) {
686
+ setQueueInterval.cancel();
687
+ }
688
+
689
+ if (setTimerIntervel != null) {
690
+ setTimerIntervel.cancel();
691
+ }
692
+ startService(new Intent(getApplicationContext(), mInterfaceService.class));
693
+ }
694
+
695
+ public boolean isConnected() {
696
+ ConnectivityManager online = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
697
+ NetworkInfo networkInfo = online.getActiveNetworkInfo();
698
+ if (networkInfo != null && networkInfo.isConnected()) {
699
+ return true;
700
+ } else {
701
+ return false;
702
+ }
703
+ }
704
+
705
+ public class CoresTimerTask extends TimerTask {
706
+ private boolean hasStarted = false;
707
+
708
+ public void run() {
709
+ this.hasStarted = true;
710
+ setLocationTimeInterval = new Timer();
711
+ try {
712
+ getPeriodicalLocationUpdates();
713
+ } catch (Exception e) {
714
+ e.printStackTrace();
715
+ }
716
+ }
717
+
718
+ public boolean hasRunStarted() {
719
+ return this.hasStarted;
720
+ }
721
+ }
722
+
723
+ public void update() throws IOException, JSONException {
724
+ TimerTask timerTask = new TimerTask() {
725
+ @Override
726
+ public void run() {
727
+ System.out.println("Updated timer");
728
+ try {
729
+ getPeriodicalLocationUpdates();
730
+ } catch (Exception e) {
731
+ e.printStackTrace();
732
+ }
733
+ }
734
+ };
735
+ String currentLine;
736
+ StringBuilder locConfigObj = new StringBuilder();
737
+ File baseDirectory = mInterfaceUtil.rootDirectory;
738
+ File locConfigFile = new File(baseDirectory, "/" + mInterfaceUtil.packageName + "/location_configuration.txt");
739
+ if (locConfigFile.exists()) {
740
+ BufferedReader readerObj = new BufferedReader(new FileReader(locConfigFile));
741
+ while ((currentLine = readerObj.readLine()) != null) {
742
+ locConfigObj.append(currentLine);
743
+ }
744
+ readerObj.close();
745
+ JSONObject serverDateObj = new JSONObject(decrypt(locConfigObj.toString()));
746
+ setLocationTimeInterval.cancel();
747
+ setLocationTimeInterval = new Timer();
748
+ setLocationTimeInterval.schedule(timerTask, Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")), Integer.parseInt(serverDateObj.optString("location_fetch_interval_in_seconds")));
749
+ }
750
+ }
751
+
752
+ }