This repository has been archived by the owner on Jun 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Aware.java
3089 lines (2665 loc) · 144 KB
/
Aware.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.aware;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.*;
import android.content.*;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.*;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.content.PermissionChecker;
import com.aware.providers.Aware_Provider;
import com.aware.providers.Aware_Provider.Aware_Device;
import com.aware.providers.Aware_Provider.Aware_Plugins;
import com.aware.providers.Aware_Provider.Aware_Settings;
import com.aware.providers.Battery_Provider;
import com.aware.providers.Scheduler_Provider;
import com.aware.utils.*;
import dalvik.system.DexFile;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Main AWARE framework service. awareContext will start and manage all the services and settings.
*
* @author denzil
*/
public class Aware extends Service {
/**
* Debug flag (default = false).
*/
public static boolean DEBUG = false;
/**
* Debug tag (default = "AWARE").
*/
public static String TAG = "AWARE";
/**
* Used to check if the core library is running or not inside individual plugins
*/
public static boolean IS_CORE_RUNNING = false;
/**
* Broadcasted event: awareContext device information is available
*/
public static final String ACTION_AWARE_DEVICE_INFORMATION = "ACTION_AWARE_DEVICE_INFORMATION";
/**
* Received broadcast on all modules
* - Sends the data to the defined webserver
*/
public static final String ACTION_AWARE_SYNC_DATA = "ACTION_AWARE_SYNC_DATA";
/**
* Received broadcast on all modules
* - Cleans the data collected on the device
*/
public static final String ACTION_AWARE_CLEAR_DATA = "ACTION_AWARE_CLEAR_DATA";
/**
* Received broadcast: this broadcast will trigger plugins that implement the CONTEXT_PRODUCER callback.
*/
public static final String ACTION_AWARE_CURRENT_CONTEXT = "ACTION_AWARE_CURRENT_CONTEXT";
/**
* Stop all plugins
*/
public static final String ACTION_AWARE_STOP_PLUGINS = "ACTION_AWARE_STOP_PLUGINS";
/**
* Stop all sensors
*/
public static final String ACTION_AWARE_STOP_SENSORS = "ACTION_AWARE_STOP_SENSORS";
/**
* Set AWARE as a foreground service. This shows a permanent notification on the screen.
*/
public static final String ACTION_AWARE_PRIORITY_FOREGROUND = "ACTION_AWARE_PRIORITY_FOREGROUND";
/**
* Set AWARE as a standard background service. May be killed or interrupted by Android at any time.
*/
public static final String ACTION_AWARE_PRIORITY_BACKGROUND = "ACTION_AWARE_PRIORITY_BACKGROUND";
/**
* Used to check users' compliance in a study
*/
public static final String ACTION_AWARE_PLUGIN_INSTALLED = "ACTION_AWARE_PLUGIN_INSTALLED";
public static final String ACTION_AWARE_PLUGIN_UNINSTALLED = "ACTION_AWARE_PLUGIN_UNINSTALLED";
public static final String EXTRA_PLUGIN = "extra_plugin";
/**
* Used by Plugin Manager to refresh UI
*/
public static final String ACTION_AWARE_UPDATE_PLUGINS_INFO = "ACTION_AWARE_UPDATE_PLUGINS_INFO";
/**
* Used when quitting a study. This will reset the device to default settings.
*/
public static final String ACTION_QUIT_STUDY = "ACTION_QUIT_STUDY";
/**
* Broadcasted when joined study successfully
*/
public static final String ACTION_JOINED_STUDY = "ACTION_JOINED_STUDY";
/**
* Used by the AWARE watchdog
*/
private static final String ACTION_AWARE_KEEP_ALIVE = "ACTION_AWARE_KEEP_ALIVE";
/**
* Used by the compliance check scheduler
*/
private static final String ACTION_AWARE_STUDY_COMPLIANCE = "ACTION_AWARE_STUDY_COMPLIANCE";
/**
* Notification ID for AWARE service as foreground (to handle Doze, Android O battery optimizations)
*/
public static final int AWARE_FOREGROUND_SERVICE = 220882;
/**
* Used on the scheduler class to define global schedules for AWARE, SYNC and SPACE MAINTENANCE actions
*/
//public static final String SCHEDULE_SYNC_DATA = "schedule_aware_sync_data";
public static final String SCHEDULE_STUDY_COMPLIANCE = "schedule_aware_study_compliance";
public static final String SCHEDULE_KEEP_ALIVE = "schedule_aware_keep_alive";
/**
* Android 8 notification channels support
*/
public static final String AWARE_NOTIFICATION_CHANNEL_GENERAL = "AWARE_NOTIFICATION_CHANNEL_GENERAL";
public static final String AWARE_NOTIFICATION_CHANNEL_SILENT = "AWARE_NOTIFICATION_CHANNEL_SILENT";
public static final String AWARE_NOTIFICATION_CHANNEL_DATASYNC = "AWARE_NOTIFICATION_CHANNEL_DATASYNC";
public static final int AWARE_NOTIFICATION_IMPORTANCE_GENERAL = NotificationManager.IMPORTANCE_HIGH;
public static final int AWARE_NOTIFICATION_IMPORTANCE_SILENT = NotificationManager.IMPORTANCE_MIN;
public static final int AWARE_NOTIFICATION_IMPORTANCE_DATASYNC = NotificationManager.IMPORTANCE_LOW;
private static Intent accelerometerSrv = null;
private static Intent locationsSrv = null;
private static Intent bluetoothSrv = null;
private static Intent screenSrv = null;
private static Intent batterySrv = null;
private static Intent networkSrv = null;
private static Intent trafficSrv = null;
private static Intent communicationSrv = null;
private static Intent processorSrv = null;
private static Intent mqttSrv = null;
private static Intent gyroSrv = null;
private static Intent wifiSrv = null;
private static Intent telephonySrv = null;
private static Intent timeZoneSrv = null;
private static Intent rotationSrv = null;
private static Intent lightSrv = null;
private static Intent proximitySrv = null;
private static Intent magnetoSrv = null;
private static Intent barometerSrv = null;
private static Intent gravitySrv = null;
private static Intent linear_accelSrv = null;
private static Intent temperatureSrv = null;
private static Intent esmSrv = null;
private static Intent installationsSrv = null;
private static Intent keyboard = null;
private static Intent scheduler = null;
private static Intent significantSrv = null;
private static Intent websocket = null;
private static AsyncStudyCheck studyCheck = null;
/**
* Variable for the Doze ignore list
*/
private static final int AWARE_BATTERY_OPTIMIZATION_ID = 567567;
/**
* Holds a reference to the AWARE account, automatically restore in each plugin.
*/
private static Account aware_account;
public String AUTHORITY = "";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
AUTHORITY = Aware_Provider.getAuthority(this);
IntentFilter storage = new IntentFilter();
storage.addAction(Intent.ACTION_MEDIA_MOUNTED);
storage.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
storage.addDataScheme("file");
registerReceiver(storage_BR, storage);
IntentFilter boot = new IntentFilter();
boot.addAction(Intent.ACTION_BOOT_COMPLETED);
boot.addAction(Intent.ACTION_SHUTDOWN);
boot.addAction(Intent.ACTION_REBOOT);
boot.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(awareBoot, boot);
IntentFilter awareActions = new IntentFilter();
awareActions.addAction(Aware.ACTION_AWARE_SYNC_DATA);
awareActions.addAction(Aware.ACTION_QUIT_STUDY);
registerReceiver(aware_BR, awareActions);
IntentFilter foreground = new IntentFilter();
foreground.addAction(Aware.ACTION_AWARE_PRIORITY_FOREGROUND);
foreground.addAction(Aware.ACTION_AWARE_PRIORITY_BACKGROUND);
registerReceiver(foregroundMgr, foreground);
IntentFilter scheduler = new IntentFilter();
scheduler.addAction(Intent.ACTION_TIME_TICK);
schedulerTicker.interval_ms = 60000 * getApplicationContext().getResources().getInteger(R.integer.alarm_wakeup_interval_min);
registerReceiver(schedulerTicker, scheduler);
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
stopSelf();
return;
}
//Android 8 specific: create notification channels for AWARE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager not_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel aware_channel = new NotificationChannel(AWARE_NOTIFICATION_CHANNEL_GENERAL, getResources().getString(R.string.app_name), AWARE_NOTIFICATION_IMPORTANCE_GENERAL);
aware_channel.setDescription(getResources().getString(R.string.channel_general_description));
aware_channel.enableLights(true);
aware_channel.setLightColor(Color.BLUE);
aware_channel.enableVibration(true);
not_manager.createNotificationChannel(aware_channel);
NotificationChannel aware_channel_sync = new NotificationChannel(AWARE_NOTIFICATION_CHANNEL_DATASYNC, getResources().getString(R.string.app_name), AWARE_NOTIFICATION_IMPORTANCE_DATASYNC);
aware_channel_sync.setDescription(getResources().getString(R.string.channel_datasync_description));
aware_channel_sync.enableLights(false);
aware_channel_sync.setLightColor(Color.BLUE);
aware_channel_sync.enableVibration(false);
aware_channel_sync.setSound(null, null);
not_manager.createNotificationChannel(aware_channel_sync);
NotificationChannel aware_channel_silent = new NotificationChannel(AWARE_NOTIFICATION_CHANNEL_SILENT, getResources().getString(R.string.app_name), AWARE_NOTIFICATION_IMPORTANCE_SILENT);
aware_channel_silent.setDescription(getResources().getString(R.string.channel_silent_description));
aware_channel_silent.enableLights(false);
aware_channel_silent.setLightColor(Color.BLUE);
aware_channel_silent.enableVibration(false);
aware_channel_silent.setSound(null, null);
not_manager.createNotificationChannel(aware_channel_silent);
}
// Start the foreground service only if it's the client or a standalone application
if ((getApplicationContext().getPackageName().equals("com.aware.phone") || getApplicationContext().getApplicationContext().getResources().getBoolean(R.bool.standalone)))
getApplicationContext().sendBroadcast(new Intent(Aware.ACTION_AWARE_PRIORITY_FOREGROUND));
if (Aware.DEBUG) Log.d(TAG, "AWARE framework is created!");
IS_CORE_RUNNING = true;
aware_account = getAWAREAccount(this);
}
/**
* Return AWARE's account
*
* @param context
* @return
*/
public static Account getAWAREAccount(Context context) {
AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
Account[] accounts = accountManager.getAccountsByType(Aware_Accounts.Aware_Account.AWARE_ACCOUNT_TYPE);
if (accounts.length > 0) {
aware_account = accounts[0];
return aware_account;
}
if (aware_account == null) {
aware_account = new Account(Aware_Accounts.Aware_Account.AWARE_ACCOUNT, Aware_Accounts.Aware_Account.AWARE_ACCOUNT_TYPE);
try {
accountManager.addAccountExplicitly(aware_account, null, null);
} catch (SecurityException e) {
e.printStackTrace();
}
}
return aware_account;
}
private final Foreground_Priority foregroundMgr = new Foreground_Priority();
public class Foreground_Priority extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//do nothing unless it's the client or a standalone application
if (!(context.getPackageName().equals("com.aware.phone") || context.getApplicationContext().getResources().getBoolean(R.bool.standalone)))
return;
if (intent.getAction().equalsIgnoreCase(Aware.ACTION_AWARE_PRIORITY_FOREGROUND)) {
if (DEBUG) Log.d(TAG, "Setting AWARE with foreground priority");
foreground(true);
} else if (intent.getAction().equalsIgnoreCase(Aware.ACTION_AWARE_PRIORITY_BACKGROUND)) {
if (DEBUG) Log.d(TAG, "Setting AWARE with background priority");
foreground(false);
}
}
}
public void foreground(boolean enable) {
if (enable) {
Intent aware = new Intent(this, Aware.class);
PendingIntent onTap = PendingIntent.getService(this, 0, aware, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Aware.AWARE_NOTIFICATION_CHANNEL_SILENT);
mBuilder.setSmallIcon(R.drawable.ic_action_aware_studies);
mBuilder.setContentTitle(getApplicationContext().getResources().getString(R.string.foreground_notification_title));
mBuilder.setContentText(getApplicationContext().getResources().getString(R.string.foreground_notification_text));
mBuilder.setOngoing(true);
mBuilder.setOnlyAlertOnce(true);
mBuilder.setContentIntent(onTap);
mBuilder = Aware.setNotificationProperties(mBuilder, AWARE_NOTIFICATION_IMPORTANCE_SILENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mBuilder.setChannelId(Aware.AWARE_NOTIFICATION_CHANNEL_SILENT);
startForeground(Aware.AWARE_FOREGROUND_SERVICE, mBuilder.build());
} else {
stopForeground(true);
}
}
// set sound/vibration/priority, mainly for android v7 and older as these are handled by channel in 8+
// TODO potentially add other variables here in the future (e.g., icon, contentTitle, etc.)
public static NotificationCompat.Builder setNotificationProperties(NotificationCompat.Builder builder, int notificationImportance) {
switch (notificationImportance) {
case AWARE_NOTIFICATION_IMPORTANCE_DATASYNC:
builder.setSound(null);
builder.setVibrate(null);
// priority low but still visible
builder.setPriority(NotificationCompat.PRIORITY_LOW);
return builder;
case AWARE_NOTIFICATION_IMPORTANCE_SILENT:
builder.setSound(null);
builder.setVibrate(null);
// priority lowest
builder.setPriority(NotificationCompat.PRIORITY_MIN);
return builder;
case AWARE_NOTIFICATION_IMPORTANCE_GENERAL:
// default sound and vibration with HIGH priority
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
return builder;
default:
return builder;
}
}
private final SchedulerTicker schedulerTicker = new SchedulerTicker();
public class SchedulerTicker extends BroadcastReceiver {
long last_time = 0;
long interval_ms = 60000; // Set in Aware class where we have context
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { //Executed every 1-minute. OS will send this tickle automatically
long ts = System.currentTimeMillis();
// Subtract 30s. The ticker only is every minute anyway, this gives us some
// slack in case the interval is slightly less than 60000ms.
if (ts > last_time + interval_ms - 30000) {
last_time = ts;
Intent scheduler = new Intent(context, Scheduler.class);
scheduler.setAction(Scheduler.ACTION_AWARE_SCHEDULER_CHECK);
context.startService(scheduler);
}
}
}
}
private class AsyncPing extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// Download the certificate, and block since we are already running in background
// and we need the certificate immediately.
SSLManager.handleUrl(getApplicationContext(), "https://api.awareframework.com/index.php", true);
//Ping AWARE's server with awareContext device's information for framework's statistics log
Hashtable<String, String> device_ping = new Hashtable<>();
device_ping.put(Aware_Preferences.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID));
device_ping.put("ping", String.valueOf(System.currentTimeMillis()));
device_ping.put("platform", "android");
try {
PackageInfo package_info = getPackageManager().getPackageInfo(getPackageName(), 0);
device_ping.put("package_name", package_info.packageName);
if (package_info.packageName.equals("com.aware.phone") || getApplicationContext().getResources().getBoolean(R.bool.standalone)) {
device_ping.put("package_version_code", String.valueOf(package_info.versionCode));
device_ping.put("package_version_name", String.valueOf(package_info.versionName));
}
} catch (PackageManager.NameNotFoundException e) {
}
try {
new Https(SSLManager.getHTTPS(getApplicationContext(), "https://api.awareframework.com/index.php")).dataPOST("https://api.awareframework.com/index.php/awaredev/alive", device_ping, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return true;
}
}
/**
* Checks if current package is not affected by Volte, Doze
* NOTE: this only works for Android OS native battery savings, not custom ones (e.g., Sony Stamina, etc).
*
* @param context
* @return
*/
public static boolean isBatteryOptimizationIgnored(Context context, String package_name) {
boolean is_ignored = true;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
is_ignored = pm.isIgnoringBatteryOptimizations(package_name);
}
if (!is_ignored) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, Aware.AWARE_NOTIFICATION_CHANNEL_GENERAL);
mBuilder.setSmallIcon(R.drawable.ic_stat_aware_recharge);
mBuilder.setContentTitle(context.getApplicationContext().getResources().getString(R.string.aware_activate_battery_optimize_ignore_title));
mBuilder.setContentText(context.getApplicationContext().getResources().getString(R.string.aware_activate_battery_optimize_ignore));
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true); //notify the user only once
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder = setNotificationProperties(mBuilder, AWARE_NOTIFICATION_IMPORTANCE_GENERAL);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mBuilder.setChannelId(Aware.AWARE_NOTIFICATION_CHANNEL_GENERAL);
Intent batteryIntent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
batteryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent clickIntent = PendingIntent.getActivity(context, 0, batteryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(clickIntent);
NotificationManager notManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notManager.notify(Aware.AWARE_BATTERY_OPTIMIZATION_ID, mBuilder.build());
}
Log.d(Aware.TAG, "Battery Optimizations: " + is_ignored);
return is_ignored;
}
private class AsyncStudyCheck extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
//Ping AWARE's server with awareContext device's information for framework's statistics log
Hashtable<String, String> studyCheck = new Hashtable<>();
studyCheck.put(Aware_Preferences.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID));
studyCheck.put("study_check", "1");
try {
String webserver = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER);
Uri url = Uri.parse(webserver);
String protocol = url.getScheme();
String study_status;
if (protocol.equalsIgnoreCase("https")) {
study_status = new Https(SSLManager.getHTTPS(getApplicationContext(), Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER))).dataPOST(Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER), studyCheck, true);
} else {
study_status = new Http().dataPOST(Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER), studyCheck, true);
}
if (study_status == null)
return true; //unable to connect to server, timeout, etc. We do nothing.
if (DEBUG)
Log.d(Aware.TAG, "Study_status: \n" + study_status);
try {
JSONArray status = new JSONArray(study_status);
JSONObject study = status.getJSONObject(0);
if (!study.optBoolean("status", false)) {
return false; //study no longer active, make clients quit the study and reset.
}
if (!study.getString("config").equalsIgnoreCase("[]")) {
JSONObject configJSON = new JSONObject(study.getString("config"));
Aware.tweakSettings(getApplicationContext(), new JSONArray().put(configJSON));
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return true;
}
@Override
protected void onCancelled(Boolean aBoolean) {
super.onCancelled(aBoolean);
studyCheck = null;
}
@Override
protected void onPostExecute(Boolean studyStatus) {
super.onPostExecute(studyStatus);
studyCheck = null;
if (!studyStatus) {
sendBroadcast(new Intent(Aware.ACTION_QUIT_STUDY));
}
}
}
private void get_device_info() {
Cursor awareContextDevice = getContentResolver().query(Aware_Device.CONTENT_URI, null, null, null, null);
if (awareContextDevice == null || !awareContextDevice.moveToFirst()) {
ContentValues rowData = new ContentValues();
rowData.put(Aware_Device.TIMESTAMP, System.currentTimeMillis());
rowData.put(Aware_Device.DEVICE_ID, Aware.getSetting(this, Aware_Preferences.DEVICE_ID));
rowData.put(Aware_Device.BOARD, Build.BOARD);
rowData.put(Aware_Device.BRAND, Build.BRAND);
rowData.put(Aware_Device.DEVICE, Build.DEVICE);
rowData.put(Aware_Device.BUILD_ID, Build.DISPLAY);
rowData.put(Aware_Device.HARDWARE, Build.HARDWARE);
rowData.put(Aware_Device.MANUFACTURER, Build.MANUFACTURER);
rowData.put(Aware_Device.MODEL, Build.MODEL);
rowData.put(Aware_Device.PRODUCT, Build.PRODUCT);
rowData.put(Aware_Device.SERIAL, Build.SERIAL);
rowData.put(Aware_Device.RELEASE, Build.VERSION.RELEASE);
rowData.put(Aware_Device.RELEASE_TYPE, Build.TYPE);
rowData.put(Aware_Device.SDK, String.valueOf(Build.VERSION.SDK_INT));
rowData.put(Aware_Device.LABEL, Aware.getSetting(this, Aware_Preferences.DEVICE_LABEL));
try {
getContentResolver().insert(Aware_Device.CONTENT_URI, rowData);
Intent deviceData = new Intent(ACTION_AWARE_DEVICE_INFORMATION);
sendBroadcast(deviceData);
if (Aware.DEBUG) Log.d(TAG, "Device information:" + rowData.toString());
} catch (SQLiteException e) {
if (Aware.DEBUG) Log.d(TAG, e.getMessage());
} catch (SQLException e) {
if (Aware.DEBUG) Log.d(TAG, e.getMessage());
}
}
if (awareContextDevice != null && !awareContextDevice.isClosed())
awareContextDevice.close();
}
/**
* Identifies if the device is a watch or a phone.
*
* @param c
* @return boolean
*/
public static boolean is_watch(Context c) {
UiModeManager uiManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
return (uiManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_WATCH);
}
/**
* Identifies if the devices is enrolled in a study. We use the latest entry in the study table and check if the participant is still enrolled
*
* @param c
* @return
*/
public static boolean isStudy(Context c) {
boolean participant = false;
Cursor study = c.getContentResolver().query(Aware_Provider.Aware_Studies.CONTENT_URI, null, null, null,
Aware_Provider.Aware_Studies.STUDY_TIMESTAMP + " DESC LIMIT 1");
if (study != null && study.moveToFirst()) {
participant = (study.getDouble(study.getColumnIndex(Aware_Provider.Aware_Studies.STUDY_EXIT)) == 0
&& study.getDouble(study.getColumnIndex(Aware_Provider.Aware_Studies.STUDY_JOINED)) > 0); //joined and still enrolled
}
if (study != null && !study.isClosed()) study.close();
return participant;
}
public static void debug(Context c, String message) {
//NOTE: only collect this aware_log if in a study for compliance checks
if (!Aware.isStudy(c)) return;
ContentValues log = new ContentValues();
log.put(Aware_Provider.Aware_Log.LOG_TIMESTAMP, System.currentTimeMillis());
log.put(Aware_Provider.Aware_Log.LOG_DEVICE_ID, Aware.getSetting(c, Aware_Preferences.DEVICE_ID));
log.put(Aware_Provider.Aware_Log.LOG_MESSAGE, message);
if (Aware.DEBUG) Log.d(TAG, "Aware_Log: \n" + log.toString());
c.getContentResolver().insert(Aware_Provider.Aware_Log.CONTENT_URI, log);
}
/**
* Fetch the cursor for a study, given the study URL, that is still enrolled
*
* @param c
* @param study_url
* @return
*/
public static Cursor getStudy(Context c, String study_url) {
return c.getContentResolver().query(Aware_Provider.Aware_Studies.CONTENT_URI, null, Aware_Provider.Aware_Studies.STUDY_URL + " LIKE '" + study_url + "%' AND " + Aware_Provider.Aware_Studies.STUDY_EXIT + "=0", null, Aware_Provider.Aware_Studies.STUDY_TIMESTAMP + " DESC LIMIT 1");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && PermissionChecker.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
return START_STICKY;
}
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (Aware.DEBUG) Log.d(TAG, "AWARE framework is active...");
//this sets the default settings to all plugins too
SharedPreferences prefs = getSharedPreferences("com.aware.phone", Context.MODE_PRIVATE);
if (prefs.getAll().isEmpty() && Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
PreferenceManager.setDefaultValues(getApplicationContext(), "com.aware.phone", Context.MODE_PRIVATE, R.xml.aware_preferences, true);
prefs.edit().commit(); //commit changes
} else {
PreferenceManager.setDefaultValues(getApplicationContext(), "com.aware.phone", Context.MODE_PRIVATE, R.xml.aware_preferences, false);
}
//this sets the default settings to all plugins too
Map<String, ?> defaults = prefs.getAll();
for (Map.Entry<String, ?> entry : defaults.entrySet()) {
if (Aware.getSetting(getApplicationContext(), entry.getKey(), "com.aware.phone").length() == 0) {
Aware.setSetting(getApplicationContext(), entry.getKey(), entry.getValue(), "com.aware.phone"); //default AWARE settings
}
}
if (Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
UUID uuid = UUID.randomUUID();
Aware.setSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID, uuid.toString(), "com.aware.phone");
}
if (Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER).length() == 0) {
Aware.setSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER, "https://api.awareframework.com/index.php");
}
DEBUG = Aware.getSetting(this, Aware_Preferences.DEBUG_FLAG).equals("true");
TAG = Aware.getSetting(this, Aware_Preferences.DEBUG_TAG).length() > 0 ? Aware.getSetting(this, Aware_Preferences.DEBUG_TAG) : TAG;
get_device_info();
if (Aware.getSetting(getApplicationContext(), Aware_Preferences.AWARE_DONATE_USAGE).equals("true")) {
new AsyncPing().execute();
}
//only the client and self-contained apps need to run the keep alive. Plugins are handled by them.
if (getApplicationContext().getPackageName().equals("com.aware.phone") || getApplicationContext().getResources().getBoolean(R.bool.standalone)) {
try {
Scheduler.Schedule watchdog = Scheduler.getSchedule(this, SCHEDULE_KEEP_ALIVE);
if (watchdog == null) {
watchdog = new Scheduler.Schedule(SCHEDULE_KEEP_ALIVE);
watchdog.setInterval(getApplicationContext().getResources().getInteger(R.integer.keep_alive_interval_min))
.setActionType(Scheduler.ACTION_TYPE_SERVICE)
.setActionIntentAction(ACTION_AWARE_KEEP_ALIVE)
.setActionClass(getPackageName() + "/" + getClass().getName());
Scheduler.saveSchedule(this, watchdog);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Set compliance checks if on a study
if ((getPackageName().equals("com.aware.phone") || getApplicationContext().getResources().getBoolean(R.bool.standalone)) && isStudy(getApplicationContext())) {
try {
Scheduler.Schedule compliance = Scheduler.getSchedule(this, Aware.SCHEDULE_STUDY_COMPLIANCE);
if (compliance == null) {
compliance = new Scheduler.Schedule(Aware.SCHEDULE_STUDY_COMPLIANCE);
compliance.setInterval(getResources().getInteger(R.integer.study_check_interval_min))
.setActionType(Scheduler.ACTION_TYPE_SERVICE)
.setActionIntentAction(Aware.ACTION_AWARE_STUDY_COMPLIANCE)
.setActionClass(getPackageName() + "/" + getClass().getName());
Scheduler.saveSchedule(this, compliance);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equalsIgnoreCase(ACTION_AWARE_STUDY_COMPLIANCE)) {
complianceStatus(getApplicationContext());
checkBatteryLeft(getApplicationContext(), false);
if (studyCheck == null && Aware.isStudy(getApplicationContext())) {
studyCheck = new AsyncStudyCheck();
studyCheck.execute();
}
}
if (intent.getAction().equalsIgnoreCase(ACTION_AWARE_KEEP_ALIVE)) {
startAWARE(getApplicationContext());
startPlugins(getApplicationContext());
}
} else {
startAWARE(getApplicationContext());
startPlugins(getApplicationContext());
}
if (Aware.isStudy(this)) {
ContentResolver.setIsSyncable(Aware.getAWAREAccount(this), Aware_Provider.getAuthority(this), 1);
ContentResolver.setSyncAutomatically(Aware.getAWAREAccount(this), Aware_Provider.getAuthority(this), true);
long frequency = Long.parseLong(Aware.getSetting(this, Aware_Preferences.FREQUENCY_WEBSERVICE)) * 60;
SyncRequest request = new SyncRequest.Builder()
.syncPeriodic(frequency, frequency / 3)
.setSyncAdapter(Aware.getAWAREAccount(this), Aware_Provider.getAuthority(this))
.setExtras(new Bundle()).build();
ContentResolver.requestSync(request);
}
} else { //storage is not available, stop plugins and sensors
stopAWARE(getApplicationContext());
stopPlugins(getApplicationContext());
}
return START_STICKY;
}
public static void checkBatteryLeft(Context context, boolean dismiss) {
if (Aware.getSetting(context, Aware_Preferences.REMIND_TO_CHARGE).equals("true")) {
final int CHARGE_REMINDER = 5555;
NotificationManager notManager = (NotificationManager) context.getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
if (dismiss) {
notManager.cancel(CHARGE_REMINDER);
} else {
Intent batt = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (batt != null && batt.getExtras() != null) {
Bundle extras = batt.getExtras();
if (extras.getInt(BatteryManager.EXTRA_LEVEL) <= 15 && extras.getInt(BatteryManager.EXTRA_STATUS) != BatteryManager.BATTERY_STATUS_CHARGING) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), Aware.AWARE_NOTIFICATION_CHANNEL_GENERAL);
mBuilder.setSmallIcon(R.drawable.ic_stat_aware_recharge);
mBuilder.setContentTitle(context.getApplicationContext().getResources().getString(R.string.app_name));
mBuilder.setContentText(context.getApplicationContext().getText(R.string.aware_battery_recharge));
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true); //notify the user only once
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder = Aware.setNotificationProperties(mBuilder, AWARE_NOTIFICATION_IMPORTANCE_GENERAL);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mBuilder.setChannelId(Aware.AWARE_NOTIFICATION_CHANNEL_GENERAL);
PendingIntent clickIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(clickIntent);
notManager.notify(CHARGE_REMINDER, mBuilder.build());
}
}
}
}
}
/**
* Stops a plugin. Expects the package name of the plugin.
*
* @param context
* @param package_name
*/
public synchronized static void stopPlugin(final Context context, final String package_name) {
PackageInfo packageInfo = PluginsManager.isInstalled(context, package_name);
if (packageInfo != null) {
PluginsManager.disablePlugin(context, package_name);
if (context.getPackageName().equals("com.aware.phone") || context.getResources().getBoolean(R.bool.standalone)) {
context.sendBroadcast(new Intent(Aware.ACTION_AWARE_UPDATE_PLUGINS_INFO)); //sync the Plugins Manager UI for running statuses
}
ComponentName componentName;
if (packageInfo.versionName.equals("bundled")) {
componentName = new ComponentName(context.getPackageName(), package_name + ".Plugin");
if (Aware.DEBUG) Log.d(Aware.TAG, "Stopping bundled: " + componentName.toString());
} else {
componentName = new ComponentName(package_name, package_name + ".Plugin");
if (Aware.DEBUG) Log.d(Aware.TAG, "Stopping external: " + componentName.toString());
}
Intent pluginIntent = new Intent();
pluginIntent.setComponent(componentName);
context.stopService(pluginIntent);
}
}
/**
* Starts a plugin using it's package name, both for bundled and unbundled plugins
*
* @param context
* @param package_name
*/
public synchronized static void startPlugin(final Context context, final String package_name) {
PackageInfo packageInfo = PluginsManager.isInstalled(context, package_name);
if (packageInfo != null) {
PluginsManager.enablePlugin(context, package_name);
if (context.getPackageName().equals("com.aware.phone") || context.getResources().getBoolean(R.bool.standalone)) {
context.sendBroadcast(new Intent(Aware.ACTION_AWARE_UPDATE_PLUGINS_INFO)); //sync the Plugins Manager UI for running statuses
}
ComponentName componentName = null;
if (packageInfo.versionName.equals("bundled")) {
componentName = new ComponentName(context.getPackageName(), package_name + ".Plugin");
if (Aware.DEBUG)
Log.d(Aware.TAG, "Initializing bundled: " + componentName.toString());
} else {
componentName = new ComponentName(package_name, package_name + ".Plugin");
if (Aware.DEBUG)
Log.d(Aware.TAG, "Initializing external: " + componentName.toString());
}
Intent pluginIntent = new Intent();
pluginIntent.setComponent(componentName);
componentName = context.startService(pluginIntent);
//Try Kotlin compatibility
if (componentName == null) {
if (packageInfo.versionName.equals("bundled")) {
componentName = new ComponentName(context.getPackageName(), package_name + ".PluginKt");
if (Aware.DEBUG)
Log.d(Aware.TAG, "Initializing bundled: " + componentName.toString());
} else {
componentName = new ComponentName(package_name, package_name + ".PluginKt");
if (Aware.DEBUG)
Log.d(Aware.TAG, "Initializing external: " + componentName.toString());
}
pluginIntent = new Intent();
pluginIntent.setComponent(componentName);
context.startService(pluginIntent);
}
}
}
private static boolean is_running(Context context, String package_name) {
ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (package_name.equals(service.service.getPackageName()))
return true;
}
return false;
}
/**
* Requests the download of a plugin given the package name from AWARE webservices or the Play Store otherwise
*
* @param context
* @param package_name
* @param is_update
*/
public static void downloadPlugin(Context context, String package_name, String study_custom_url, boolean is_update) {
Intent pluginIntent = new Intent(context, DownloadPluginService.class);
pluginIntent.putExtra("package_name", package_name);
pluginIntent.putExtra("is_update", is_update);
if (study_custom_url != null) pluginIntent.putExtra("study_url", study_custom_url);
context.startService(pluginIntent);
}
/**
* Given a plugin's package name, fetch the context card for reuse.
*
* @param context: application context
* @param package_name: plugin's package name
* @return View for reuse
*/
public static View getContextCard(final Context context, final String package_name) {
boolean is_bundled = false;
PackageInfo pkg = PluginsManager.isInstalled(context, package_name);
if (pkg != null && pkg.versionName.equals("bundled")) {
is_bundled = true;
}
try {
String contextCardClass = ((is_bundled) ? context.getPackageName() + "/" + package_name : package_name) + ".ContextCard";
Context reflectedContext = context.createPackageContext(((is_bundled) ? context.getPackageName() : package_name), Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY);
Class<?> reflectedContextCard = reflectedContext.getClassLoader().loadClass(contextCardClass);
Object contextCard = reflectedContextCard.newInstance();
Method getContextCard = contextCard.getClass().getDeclaredMethod("getContextCard", Context.class);
getContextCard.setAccessible(true);
View ui = (View) getContextCard.invoke(contextCard, reflectedContext);
if (ui != null) {
ui.setBackgroundColor(Color.WHITE);
ui.setPadding(0, 0, 0, 10);
LinearLayout card = new LinearLayout(context);
LinearLayout.LayoutParams card_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
card.setLayoutParams(card_params);
card.setOrientation(LinearLayout.VERTICAL);
LinearLayout info = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
info.setLayoutParams(params);
info.setOrientation(LinearLayout.HORIZONTAL);
info.setBackgroundColor(Color.parseColor("#33B5E5"));
TextView plugin_header = new TextView(context);
plugin_header.setText(PluginsManager.getPluginName(context, package_name));
plugin_header.setTextColor(Color.WHITE);
plugin_header.setPadding(16, 0, 0, 0);
params.gravity = android.view.Gravity.CENTER_VERTICAL;
plugin_header.setLayoutParams(params);
info.addView(plugin_header);
//Check if plugin has settings. Add button if it does.
if (isClassAvailable(context, package_name, "Settings")) {
ImageView infoSettings = new ImageView(context);
infoSettings.setBackgroundResource(R.drawable.ic_action_plugin_settings);
infoSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean is_bundled = false;
PackageInfo pkg = PluginsManager.isInstalled(context, package_name);
if (pkg != null && pkg.versionName.equals("bundled")) {
is_bundled = true;
}
Intent open_settings = new Intent();
open_settings.setComponent(new ComponentName(((is_bundled) ? context.getPackageName() : package_name), package_name + ".Settings"));
open_settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(open_settings);
}
});
ViewGroup.LayoutParams paramsHeader = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
paramsHeader.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 46, context.getResources().getDisplayMetrics());
paramsHeader.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 46, context.getResources().getDisplayMetrics());
infoSettings.setLayoutParams(paramsHeader);
info.addView(infoSettings);
//Add settings shortcut to card
card.addView(info);
}
//Add inflated UI to card
card.addView(ui);
return card;
} else {
return new View(context);
}
} catch (InstantiationException | NoSuchMethodException | NameNotFoundException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {