/
TimeOfDay.java
executable file
·516 lines (397 loc) · 20.2 KB
/
TimeOfDay.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
package com.audacious_software.passive_data_kit.generators.environment;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.audacious_software.passive_data_kit.DeviceInformation;
import com.audacious_software.passive_data_kit.PassiveDataKit;
import com.audacious_software.passive_data_kit.activities.generators.DataPointViewHolder;
import com.audacious_software.passive_data_kit.activities.generators.RequestPermissionActivity;
import com.audacious_software.passive_data_kit.diagnostics.DiagnosticAction;
import com.audacious_software.passive_data_kit.generators.Generator;
import com.audacious_software.passive_data_kit.generators.Generators;
import com.audacious_software.pdk.passivedatakit.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
public class TimeOfDay extends Generator implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String GENERATOR_IDENTIFIER = "pdk-time-of-day";
private static final String DATABASE_PATH = "pdk-time-of-day.sqlite";
private static final String ENABLED = "com.audacious_software.passive_data_kit.generators.environment.TimeOfDay.ENABLED";
private static final boolean ENABLED_DEFAULT = true;
private static final String DATA_RETENTION_PERIOD = "com.audacious_software.passive_data_kit.generators.environment.TimeOfDay.DATA_RETENTION_PERIOD";
private static final long DATA_RETENTION_PERIOD_DEFAULT = (60 * 24 * 60 * 60 * 1000);
private static final String USE_GOOGLE_SERVICES = "com.audacious_software.passive_data_kit.generators.environment.TimeOfDay.USE_GOOGLE_SERVICES";
private static final boolean USE_GOOGLE_SERVICES_DEFAULT = true;
private static final String INCLUDE_LOCATION = "com.audacious_software.passive_data_kit.generators.environment.TimeOfDay.INCLUDE_LOCATION";
private static final boolean INCLUDE_LOCATION_DEFAULT = false;
public static final int TIME_OF_DAY_MORNING = 0;
public static final int TIME_OF_DAY_AFTERNOON = 1;
public static final int TIME_OF_DAY_EVENING = 2;
public static final int TIME_OF_DAY_NIGHT = 3;
public static final int TIME_OF_DAY_UNKNOWN = -1;
private static TimeOfDay sInstance = null;
private GoogleApiClient mGoogleApiClient = null;
private long mUpdateInterval = 300000;
private boolean mIncludeLocation = TimeOfDay.INCLUDE_LOCATION_DEFAULT;
private SQLiteDatabase mDatabase = null;
private static final int DATABASE_VERSION = 1;
private static final String TABLE_HISTORY = "history";
public static final String HISTORY_OBSERVED = "observed";
public static final String HISTORY_LATITUDE = "latitude";
public static final String HISTORY_LONGITUDE = "longitude";
public static final String HISTORY_TIMEZONE = "timezone";
public static final String HISTORY_SUNRISE = "sunrise";
public static final String HISTORY_SUNSET = "sunset";
private long mSunrise = 0;
private long mSunset = 0;
public static String generatorIdentifier() {
return TimeOfDay.GENERATOR_IDENTIFIER;
}
public static TimeOfDay getInstance(Context context) {
if (TimeOfDay.sInstance == null) {
TimeOfDay.sInstance = new TimeOfDay(context.getApplicationContext());
}
return TimeOfDay.sInstance;
}
private TimeOfDay(Context context) {
super(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.mIncludeLocation = prefs.getBoolean(TimeOfDay.INCLUDE_LOCATION, TimeOfDay.INCLUDE_LOCATION_DEFAULT);
}
public static void start(final Context context) {
TimeOfDay.getInstance(context).startGenerator();
}
@Override
public List<Bundle> fetchPayloads() {
return null;
}
private void startGenerator() {
final TimeOfDay me = this;
Runnable r = new Runnable()
{
@Override
public void run() {
if (TimeOfDay.useKindleLocationServices())
{
// TODO
throw new RuntimeException("Throw rocks at developer to implement Kindle support.");
}
else if (TimeOfDay.useGoogleLocationServices(me.mContext))
{
if (me.mGoogleApiClient == null) {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(me.mContext);
builder.addConnectionCallbacks(me);
builder.addOnConnectionFailedListener(me);
builder.addApi(LocationServices.API);
me.mGoogleApiClient = builder.build();
me.mGoogleApiClient.connect();
}
}
else
{
// TODO
throw new RuntimeException("Throw rocks at developer to implement generic location support.");
}
}
};
Thread t = new Thread(r);
t.start();
Generators.getInstance(this.mContext).registerCustomViewClass(TimeOfDay.GENERATOR_IDENTIFIER, TimeOfDay.class);
File path = PassiveDataKit.getGeneratorsStorage(this.mContext);
path = new File(path, TimeOfDay.DATABASE_PATH);
this.mDatabase = SQLiteDatabase.openOrCreateDatabase(path, null);
int version = this.getDatabaseVersion(this.mDatabase);
switch (version) {
case 0:
this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_time_of_day_create_history_table));
}
this.setDatabaseVersion(this.mDatabase, TimeOfDay.DATABASE_VERSION);
}
private void stopGenerator() {
if (this.mGoogleApiClient != null) {
this.mGoogleApiClient.disconnect();
this.mGoogleApiClient = null;
}
this.mDatabase.close();
this.mDatabase = null;
}
@SuppressWarnings("WeakerAccess")
public static boolean useGoogleLocationServices(Context context) {
SharedPreferences prefs = Generators.getInstance(context).getSharedPreferences(context);
return prefs.getBoolean(TimeOfDay.USE_GOOGLE_SERVICES, TimeOfDay.USE_GOOGLE_SERVICES_DEFAULT);
}
@SuppressWarnings("WeakerAccess")
public static boolean useKindleLocationServices() {
return DeviceInformation.isKindleFire();
}
@SuppressWarnings("WeakerAccess")
public static boolean isEnabled(Context context) {
SharedPreferences prefs = Generators.getInstance(context).getSharedPreferences(context);
return prefs.getBoolean(TimeOfDay.ENABLED, TimeOfDay.ENABLED_DEFAULT);
}
@SuppressWarnings({"Contract", "WeakerAccess"})
public static boolean isRunning(Context context) {
if (TimeOfDay.sInstance == null) {
return false;
}
if (TimeOfDay.useKindleLocationServices()) {
// TODO
throw new RuntimeException("Throw rocks at developer to implement Kindle support.");
} else if (TimeOfDay.useGoogleLocationServices(context)) {
return (TimeOfDay.sInstance.mGoogleApiClient != null);
} else {
// TODO
throw new RuntimeException("Throw rocks at developer to implement generic location support.");
}
}
@SuppressWarnings("unused")
public static ArrayList<DiagnosticAction> diagnostics(Context context)
{
return TimeOfDay.getInstance(context).runDiagostics();
}
private ArrayList<DiagnosticAction> runDiagostics() {
ArrayList<DiagnosticAction> actions = new ArrayList<>();
final TimeOfDay me = this;
final Handler handler = new Handler(Looper.getMainLooper());
if (TimeOfDay.isEnabled(this.mContext)) {
int permissionCheck = ContextCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
actions.add(new DiagnosticAction(me.mContext.getString(R.string.diagnostic_missing_location_permission_title), me.mContext.getString(R.string.diagnostic_missing_location_permission), new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(me.mContext, RequestPermissionActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(RequestPermissionActivity.PERMISSION, Manifest.permission.ACCESS_FINE_LOCATION);
me.mContext.startActivity(intent);
}
});
}
}));
}
}
return actions;
}
@Override
public void onConnected(Bundle bundle) {
final LocationRequest request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_LOW_POWER);
request.setFastestInterval(this.mUpdateInterval);
request.setInterval(this.mUpdateInterval);
if (this.mGoogleApiClient != null && this.mGoogleApiClient.isConnected()) {
if (ContextCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient, request, this, this.mContext.getMainLooper());
}
}
}
@Override
public void onConnectionSuspended(int i) {
if (this.mGoogleApiClient != null && this.mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.removeLocationUpdates(this.mGoogleApiClient, this);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
this.mGoogleApiClient = null;
}
@Override
public void onLocationChanged(android.location.Location location) {
if (location == null)
return;
com.luckycatlabs.sunrisesunset.dto.Location calcLocation = new com.luckycatlabs.sunrisesunset.dto.Location("" + location.getLatitude(), "" + location.getLongitude());
TimeZone timezone = TimeZone.getDefault();
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(calcLocation, timezone.getDisplayName());
Calendar now = Calendar.getInstance();
Calendar sunrise = calculator.getOfficialSunriseCalendarForDate(now);
Calendar sunset = calculator.getOfficialSunsetCalendarForDate(now);
if (sunrise.getTimeInMillis() > sunset.getTimeInMillis()) {
sunset.add(Calendar.DATE, 1);
}
ContentValues values = new ContentValues();
values.put(TimeOfDay.HISTORY_OBSERVED, System.currentTimeMillis());
values.put(TimeOfDay.HISTORY_LATITUDE, location.getLatitude());
values.put(TimeOfDay.HISTORY_LONGITUDE, location.getLongitude());
values.put(TimeOfDay.HISTORY_TIMEZONE, timezone.getDisplayName());
values.put(TimeOfDay.HISTORY_SUNRISE, sunrise.getTimeInMillis());
values.put(TimeOfDay.HISTORY_SUNSET, sunset.getTimeInMillis());
Bundle updated = new Bundle();
updated.putLong(TimeOfDay.HISTORY_OBSERVED, System.currentTimeMillis());
if (this.mIncludeLocation) {
updated.putDouble(TimeOfDay.HISTORY_LATITUDE, location.getLatitude());
updated.putDouble(TimeOfDay.HISTORY_LONGITUDE, location.getLongitude());
Bundle metadata = new Bundle();
metadata.putDouble(Generator.LATITUDE, location.getLatitude());
metadata.putDouble(Generator.LONGITUDE, location.getLongitude());
updated.putBundle(Generator.PDK_METADATA, metadata);
}
updated.putString(TimeOfDay.HISTORY_TIMEZONE, timezone.getDisplayName());
updated.putLong(TimeOfDay.HISTORY_SUNRISE, sunrise.getTimeInMillis());
updated.putLong(TimeOfDay.HISTORY_SUNSET, sunset.getTimeInMillis());
this.mDatabase.insert(TimeOfDay.TABLE_HISTORY, null, values);
Log.e("PDK", "TIME OF DAY BUNDLE: " + updated);
Generators.getInstance(this.mContext).notifyGeneratorUpdated(TimeOfDay.GENERATOR_IDENTIFIER, updated);
this.mSunrise = sunrise.getTimeInMillis();
this.mSunset = sunset.getTimeInMillis();
this.flushCachedData();
}
@SuppressWarnings("unused")
public static long latestPointGenerated(Context context) {
long timestamp = 0;
TimeOfDay me = TimeOfDay.getInstance(context);
Cursor c = me.mDatabase.query(TimeOfDay.TABLE_HISTORY, null, null, null, null, null, TimeOfDay.HISTORY_OBSERVED + " DESC");
if (c.moveToNext()) {
timestamp = c.getLong(c.getColumnIndex(TimeOfDay.HISTORY_OBSERVED));
}
c.close();
return timestamp;
}
public void setIncludeLocation(boolean include) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
SharedPreferences.Editor e = prefs.edit();
e.putBoolean(TimeOfDay.INCLUDE_LOCATION, include);
e.apply();
this.mIncludeLocation = true;
}
public long getSunrise() {
return this.mSunrise;
}
public long getSunset() {
return this.mSunset;
}
public int getTimeOfDay() {
if (this.mSunrise == 0 || this.mSunset == 0) {
return TIME_OF_DAY_UNKNOWN;
}
long now = System.currentTimeMillis();
Calendar noon = Calendar.getInstance();
noon.setTimeInMillis(now);
noon.set(Calendar.HOUR_OF_DAY, 12);
noon.set(Calendar.MINUTE, 0);
noon.set(Calendar.SECOND, 0);
noon.set(Calendar.MILLISECOND, 0);
if (now < this.mSunrise) {
return TimeOfDay.TIME_OF_DAY_NIGHT;
} else if (now < noon.getTimeInMillis()) {
return TimeOfDay.TIME_OF_DAY_MORNING;
} else if (now < this.mSunset - (60 * 60 * 1000)) {
return TimeOfDay.TIME_OF_DAY_AFTERNOON;
} else if (now < this.mSunset + (60 * 60 * 1000)) {
return TimeOfDay.TIME_OF_DAY_EVENING;
}
return TimeOfDay.TIME_OF_DAY_NIGHT;
}
@Override
protected void flushCachedData() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
long retentionPeriod = prefs.getLong(TimeOfDay.DATA_RETENTION_PERIOD, TimeOfDay.DATA_RETENTION_PERIOD_DEFAULT);
long start = System.currentTimeMillis() - retentionPeriod;
String where = TimeOfDay.HISTORY_OBSERVED + " < ?";
String[] args = { "" + start };
this.mDatabase.delete(TimeOfDay.TABLE_HISTORY, where, args);
}
@Override
public void setCachedDataRetentionPeriod(long period) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
SharedPreferences.Editor e = prefs.edit();
e.putLong(TimeOfDay.DATA_RETENTION_PERIOD, period);
e.apply();
}
@SuppressWarnings("unused")
public static View fetchView(ViewGroup parent) {
if (TimeOfDay.useKindleLocationServices()) {
// TODO
throw new RuntimeException("Throw rocks at developer to implement Kindle support.");
} else if (TimeOfDay.useGoogleLocationServices(parent.getContext())) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.card_generator_time_of_day, parent, false);
} else {
// TODO
throw new RuntimeException("Throw rocks at developer to implement generic location support.");
}
}
@SuppressWarnings({"UnusedAssignment", "unused"})
public static void bindViewHolder(DataPointViewHolder holder) {
final Context context = holder.itemView.getContext();
TimeOfDay me = TimeOfDay.getInstance(context);
long timestamp = 0;
Cursor c = me.mDatabase.query(TimeOfDay.TABLE_HISTORY, null, null, null, null, null, TimeOfDay.HISTORY_OBSERVED + " DESC");
if (c.moveToNext()) {
timestamp = c.getLong(c.getColumnIndex(TimeOfDay.HISTORY_OBSERVED));
}
View cardEmpty = holder.itemView.findViewById(R.id.card_empty);
View cardContent = holder.itemView.findViewById(R.id.card_content);
TextView dateLabel = (TextView) holder.itemView.findViewById(R.id.generator_data_point_date);
if (timestamp > 0) {
dateLabel.setText(Generator.formatTimestamp(context, timestamp / 1000));
cardEmpty.setVisibility(View.GONE);
cardContent.setVisibility(View.VISIBLE);
View nightMorning = cardContent.findViewById(R.id.cell_night_morning);
View morning = cardContent.findViewById(R.id.cell_morning);
View afternoon = cardContent.findViewById(R.id.cell_afternoon);
View evening = cardContent.findViewById(R.id.cell_evening);
View nightNight = cardContent.findViewById(R.id.cell_night_night);
nightMorning.setAlpha(0.5f);
morning.setAlpha(0.5f);
afternoon.setAlpha(0.5f);
evening.setAlpha(0.5f);
nightNight.setAlpha(0.5f);
switch (me.getTimeOfDay()) {
case TIME_OF_DAY_NIGHT:
Calendar now = Calendar.getInstance();
if (now.get(Calendar.HOUR_OF_DAY) < 12) {
nightMorning.setAlpha(1.0f);
} else {
nightNight.setAlpha(1.0f);
}
break;
case TIME_OF_DAY_MORNING:
morning.setAlpha(1.0f);
break;
case TIME_OF_DAY_AFTERNOON:
afternoon.setAlpha(1.0f);
break;
case TIME_OF_DAY_EVENING:
evening.setAlpha(1.0f);
break;
}
DateFormat format = android.text.format.DateFormat.getTimeFormat(context);
TextView sunrise = (TextView) cardContent.findViewById(R.id.label_sunrise);
Calendar sunriseCalendar = Calendar.getInstance();
sunriseCalendar.setTimeInMillis(me.mSunrise);
sunrise.setText(format.format(sunriseCalendar.getTime()));
TextView sunset = (TextView) cardContent.findViewById(R.id.label_sunset);
Calendar sunsetCalendar = Calendar.getInstance();
sunsetCalendar.setTimeInMillis(me.mSunset);
sunset.setText(format.format(sunsetCalendar.getTime()));
} else {
dateLabel.setText(R.string.label_never_pdk);
cardEmpty.setVisibility(View.VISIBLE);
cardContent.setVisibility(View.GONE);
}
}
}