-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathScheduler.java
More file actions
856 lines (788 loc) · 35.2 KB
/
Scheduler.java
File metadata and controls
856 lines (788 loc) · 35.2 KB
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
package dk.jens.backup.schedules;
import android.app.AlarmManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.LongSparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.annimon.stream.Optional;
import dk.jens.backup.BaseActivity;
import dk.jens.backup.BlacklistContract;
import dk.jens.backup.BlacklistListener;
import dk.jens.backup.BlacklistsDBHelper;
import dk.jens.backup.Constants;
import dk.jens.backup.FileCreationHelper;
import dk.jens.backup.FileReaderWriter;
import dk.jens.backup.R;
import dk.jens.backup.Utils;
import dk.jens.backup.schedules.db.Schedule;
import dk.jens.backup.schedules.db.ScheduleDao;
import dk.jens.backup.schedules.db.ScheduleDatabase;
import dk.jens.backup.schedules.db.ScheduleDatabaseHelper;
import dk.jens.backup.ui.dialogs.BlacklistDialogFragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
public class Scheduler extends BaseActivity
implements View.OnClickListener, AdapterView.OnItemSelectedListener,
BlacklistListener
{
private static final String TAG = Constants.TAG;
public static final String SCHEDULECUSTOMLIST = "customlist";
static final int CUSTOMLISTUPDATEBUTTONID = 1;
static final int EXCLUDESYSTEMCHECKBOXID = 2;
public static final int GLOBALBLACKLISTID = -1;
static String DATABASE_NAME = "schedules.db";
LongSparseArray<View> viewList;
HandleAlarms handleAlarms;
int totalSchedules;
SharedPreferences defaultPrefs;
private BlacklistsDBHelper blacklistsDBHelper;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.schedulesframe);
handleAlarms = new HandleAlarms(this);
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
viewList = new LongSparseArray<>();
blacklistsDBHelper = new BlacklistsDBHelper(this);
}
@Override
public void onResume()
{
super.onResume();
for(int i = 0; i < viewList.size(); i++)
{
final View view = viewList.valueAt(i);
android.view.ViewGroup parent = (android.view.ViewGroup) view.getParent();
if(parent != null)
parent.removeView(view);
}
new UiLoaderTask(this).execute();
}
private void populateViews(List<Schedule> schedules) {
final LinearLayout mainLayout = findViewById(R.id.linearLayout);
viewList = new LongSparseArray<>();
for(Schedule schedule : schedules) {
final View v = buildUi(schedule);
viewList.put(schedule.getId(), v);
mainLayout.addView(v);
if(schedule.isEnabled()) {
setTimeLeftTextView(schedule, v);
}
}
}
@Override
public void onDestroy() {
blacklistsDBHelper.close();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.clear();
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.schedulesmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.addSchedule:
new AddScheduleTask(this).execute();
return true;
case R.id.globalBlacklist:
new Thread(() -> {
Bundle args = new Bundle();
args.putInt(Constants.BLACKLIST_ARGS_ID, GLOBALBLACKLISTID);
SQLiteDatabase db = blacklistsDBHelper.getReadableDatabase();
ArrayList<String> blacklistedPackages = blacklistsDBHelper
.getBlacklistedPackages(db, GLOBALBLACKLISTID);
args.putStringArrayList(Constants.BLACKLIST_ARGS_PACKAGES,
blacklistedPackages);
BlacklistDialogFragment blacklistDialogFragment = new BlacklistDialogFragment();
blacklistDialogFragment.setArguments(args);
blacklistDialogFragment.addBlacklistListener(this);
blacklistDialogFragment.show(getFragmentManager(), "blacklistDialog");
}).start();
return true;
}
return super.onOptionsItemSelected(item);
}
private View buildUiForNewSchedule(String databasename) {
final Schedule schedule = new Schedule.Builder()
// Set id to 0 to make the database generate a new id
.withId(0)
.build();
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(this, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
final long[] ids = scheduleDao.insert(schedule);
// update schedule id with one generated by the database
schedule.setId(ids[0]);
return buildUi(schedule);
}
public View buildUi(Schedule schedule) {
View view = LayoutInflater.from(this).inflate(R.layout.schedule, null);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);
Button updateButton = (Button) view.findViewById(R.id.updateButton);
updateButton.setOnClickListener(this);
Button removeButton = (Button) view.findViewById(R.id.removeButton);
removeButton.setOnClickListener(this);
Button activateButton = (Button) view.findViewById(R.id.activateButton);
activateButton.setOnClickListener(this);
EditText intervalDays = (EditText) view.findViewById(R.id.intervalDays);
final String repeatString = Integer.toString(
schedule.getInterval());
intervalDays.setText(repeatString);
EditText timeOfDay = (EditText) view.findViewById(R.id.timeOfDay);
final String timeOfDayString = Integer.toString(
schedule.getHour());
timeOfDay.setText(timeOfDayString);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
cb.setChecked(schedule.isEnabled());
Spinner spinner = (Spinner) view.findViewById(R.id.sched_spinner);
Spinner spinnerSubModes = (Spinner) view.findViewById(R.id.sched_spinnerSubModes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.scheduleModes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// false has the effect that onItemSelected() is not called when
// the spinner is added
spinner.setSelection(schedule.getMode().getValue(), false);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapterSubModes = ArrayAdapter.createFromResource(this, R.array.scheduleSubModes, android.R.layout.simple_spinner_item);
adapterSubModes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSubModes.setAdapter(adapterSubModes);
spinnerSubModes.setSelection(schedule.getSubmode().getValue(),
false);
spinnerSubModes.setOnItemSelectedListener(this);
final long number = schedule.getId();
toggleSecondaryButtons(ll, spinner, number);
view.setTag(number);
updateButton.setTag(number);
removeButton.setTag(number);
activateButton.setTag(number);
cb.setTag(number);
spinner.setTag(number);
spinnerSubModes.setTag(number);
return view;
}
public void checkboxOnClick(View v)
{
final long number = (long) v.getTag();
try {
final View scheduleView = viewList.get(number);
final Schedule schedule = getScheduleDataFromView(
scheduleView, (int)number);
final UpdateScheduleRunnable updateScheduleRunnable =
new UpdateScheduleRunnable(this, DATABASE_NAME, schedule);
new Thread(updateScheduleRunnable).start();
if(!schedule.isEnabled()) {
handleAlarms.cancelAlarm((int)number);
}
setTimeLeftTextView(schedule, scheduleView);
} catch (SchedulingException e) {
final String message = String.format(
"Unable to enable schedule %s: %s", number, e.toString());
Log.e(TAG, message);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v)
{
/*
* First cast the tag to long and then cast that long to int
* this is necessary for the time being because the tag contains
* the schedule id which comes from the database but is used by
* AlarmManager-related methods which expect int values.
* This should obviously be fixed.
*/
final int number = (int) (long) v.getTag();
try
{
View view = viewList.get(number);
switch(v.getId())
{
case EXCLUDESYSTEMCHECKBOXID:
case R.id.updateButton:
updateScheduleData(view, number);
break;
case R.id.removeButton:
new RemoveScheduleTask(this).execute((long)number);
break;
case R.id.activateButton:
Utils.showConfirmDialog(this, "", getString(R.string.sched_activateButton),
new StartSchedule(this, new HandleScheduledBackups(
this), number, DATABASE_NAME));
break;
case CUSTOMLISTUPDATEBUTTONID:
CustomPackageList.showList(this, number);
break;
}
}
catch(IndexOutOfBoundsException e)
{
Log.e(TAG, String.format(
"Caught unexpected exception while handling onClick for schedule %s: %s",
number, e));
}
}
private void updateScheduleData(View scheduleView, int id) {
try {
final Schedule schedule = getScheduleDataFromView(
scheduleView, id);
UpdateScheduleRunnable updateScheduleRunnable =
new UpdateScheduleRunnable(this, DATABASE_NAME, schedule);
new Thread(updateScheduleRunnable).start();
setTimeLeftTextView(schedule, scheduleView);
} catch (SchedulingException e) {
Log.e(TAG, String.format("Unable to update schedule %s",
id));
Toast.makeText(this, String.format(
"Unable to update schedule %s", id),
Toast.LENGTH_LONG).show();
}
}
private Schedule getScheduleDataFromView(View scheduleView, int id)
throws SchedulingException {
final EditText intervalText = scheduleView.findViewById(
R.id.intervalDays);
final EditText hourText = scheduleView.findViewById(
R.id.timeOfDay);
final Spinner modeSpinner = scheduleView.findViewById(
R.id.sched_spinner);
final Spinner submodeSpinner = scheduleView.findViewById(
R.id.sched_spinnerSubModes);
final CheckBox excludeSystemCheckbox = scheduleView.findViewById(
EXCLUDESYSTEMCHECKBOXID);
final boolean excludeSystemPackages = excludeSystemCheckbox != null
&& excludeSystemCheckbox.isChecked();
final CheckBox enabledCheckbox = scheduleView.findViewById(
R.id.checkbox);
final boolean enabled = enabledCheckbox.isChecked();
final int hour = Integer.parseInt(hourText.getText()
.toString());
final int interval = Integer.parseInt(intervalText
.getText().toString());
if (enabled) {
handleAlarms.setAlarm(id, interval, hour);
}
return new Schedule.Builder()
.withId(id)
.withHour(hour)
.withInterval(interval)
.withMode(modeSpinner.getSelectedItemPosition())
.withSubmode(submodeSpinner.getSelectedItemPosition())
.withPlaced(System.currentTimeMillis())
.withEnabled(enabled)
.withExcludeSystem(excludeSystemPackages)
.build();
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
final long number = (long) parent.getTag();
final int spinnerId = parent.getId();
if(spinnerId == R.id.sched_spinner) {
toggleSecondaryButtons((LinearLayout) parent.getParent(), (Spinner) parent, number);
if (pos == 4) {
CustomPackageList.showList(this, number);
}
changeScheduleMode(pos, number);
} else if(spinnerId == R.id.sched_spinnerSubModes) {
changeScheduleSubmode(pos, number);
}
}
public void onNothingSelected(AdapterView<?> parent)
{}
private void changeScheduleMode(int modeInt, long id) {
try {
final Schedule.Mode mode = Schedule.Mode.intToMode(modeInt);
final ModeChangerRunnable modeChangerRunnable =
new ModeChangerRunnable(this, id, mode);
new Thread(modeChangerRunnable).start();
} catch (SchedulingException e) {
final String message = String.format(
"Unable to set mode of schedule %s to %s", id, modeInt);
Log.e(TAG, message);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
private void changeScheduleSubmode(int submodeInt, long id) {
try {
final Schedule.Submode submode = Schedule.Submode.intToSubmode(
submodeInt);
final ModeChangerRunnable modeChangerRunnable =
new ModeChangerRunnable(this, id, submode);
new Thread(modeChangerRunnable).start();
} catch (SchedulingException e) {
final String message = String.format(
"Unable to set submode of schedule %s to %s", id, submodeInt);
Log.e(TAG, message);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onBlacklistChanged(CharSequence[] blacklist, int id) {
new Thread(() -> {
SQLiteDatabase db = blacklistsDBHelper.getWritableDatabase();
blacklistsDBHelper.deleteBlacklistFromId(db, id);
for(CharSequence packagename : blacklist) {
ContentValues values = new ContentValues();
values.put(BlacklistContract.BlacklistEntry.COLUMN_PACKAGENAME, (String) packagename);
values.put(BlacklistContract.BlacklistEntry.COLUMN_BLACKLISTID, String.valueOf(id));
db.insert(BlacklistContract.BlacklistEntry.TABLE_NAME, null, values);
}
}).start();
}
private void setTimeLeftTextView(Schedule schedule, View view) {
setTimeLeftTextView(schedule, view, System.currentTimeMillis());
}
void setTimeLeftTextView(Schedule schedule, View view, long now) {
final TextView timeLeftTextView = view.findViewById(R.id.sched_timeLeft);
if(!schedule.isEnabled()) {
timeLeftTextView.setText("");
} else if(schedule.getInterval() <= 0) {
timeLeftTextView.setText(getString(R.string.sched_warningIntervalZero));
} else {
final long timeLeft = handleAlarms.timeUntilNextEvent(
schedule.getInterval(), schedule.getHour(),
schedule.getPlaced(), now);
timeLeftTextView.setText(getString(R.string.sched_timeLeft) + ": " + (timeLeft / 1000f / 60 / 60f));
}
}
public void toggleSecondaryButtons(LinearLayout parent, Spinner spinner, long number)
{
switch(spinner.getSelectedItemPosition())
{
case 3:
if(parent.findViewById(EXCLUDESYSTEMCHECKBOXID) != null) {
break;
}
CheckBox cb = new CheckBox(this);
cb.setId(EXCLUDESYSTEMCHECKBOXID);
cb.setText(getString(R.string.sched_excludeSystemCheckBox));
cb.setTag(number);
new SystemExcludeCheckboxSetTask(this, number, cb).execute();
cb.setOnClickListener(this);
LayoutParams cblp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
parent.addView(cb, cblp);
removeSecondaryButton(parent, cb);
break;
case 4:
if(parent.findViewById(CUSTOMLISTUPDATEBUTTONID) != null) {
break;
}
Button bt = new Button(this);
bt.setId(CUSTOMLISTUPDATEBUTTONID);
bt.setText(getString(R.string.sched_customListUpdateButton));
bt.setTag(number);
bt.setOnClickListener(this);
LayoutParams btlp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
parent.addView(bt, btlp);
removeSecondaryButton(parent, bt);
break;
default:
removeSecondaryButton(parent, null);
break;
}
}
public static void removeSecondaryButton(LinearLayout parent, View v)
{
int id = (v != null) ? v.getId() : -1;
Button bt = (Button) parent.findViewById(CUSTOMLISTUPDATEBUTTONID);
CheckBox cb = (CheckBox) parent.findViewById(EXCLUDESYSTEMCHECKBOXID);
if(bt != null && id != CUSTOMLISTUPDATEBUTTONID)
{
parent.removeView(bt);
}
if(cb != null && id != EXCLUDESYSTEMCHECKBOXID)
{
parent.removeView(cb);
}
}
void migrateSchedulesToDatabase(SharedPreferences preferences,
String databasename) throws SchedulingException {
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(this, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
for(int i = 0; i < totalSchedules; i++) {
final Schedule schedule = Schedule.fromPreferences(preferences,
i);
// The database is one-indexed so in order to preserve the
// order of the inserted schedules we have to increment the id.
schedule.setId(i + 1L);
try {
final long[] ids = scheduleDao.insert(schedule);
// TODO: throw an exception if renaming failed. This requires
// the renaming logic to propagate errors properly.
renameCustomListFile(i, ids[0]);
removePreferenceEntries(preferences, i);
if (schedule.isEnabled()) {
handleAlarms.cancelAlarm(i);
handleAlarms.setAlarm((int) ids[0],
schedule.getInterval(), schedule.getHour());
}
} catch (SQLException e) {
throw new SchedulingException(
"Unable to migrate schedules to database", e);
}
}
}
public void removePreferenceEntries(SharedPreferences preferences,
int number) {
final SharedPreferences.Editor editor = preferences.edit();
editor.remove(Constants.PREFS_SCHEDULES_ENABLED + number);
editor.remove(Constants.PREFS_SCHEDULES_EXCLUDESYSTEM + number);
editor.remove(Constants.PREFS_SCHEDULES_HOUROFDAY + number);
editor.remove(Constants.PREFS_SCHEDULES_REPEATTIME + number);
editor.remove(Constants.PREFS_SCHEDULES_MODE + number);
editor.remove(Constants.PREFS_SCHEDULES_SUBMODE + number);
editor.remove(Constants.PREFS_SCHEDULES_TIMEPLACED + number);
editor.remove(Constants.PREFS_SCHEDULES_TIMEUNTILNEXTEVENT + number);
editor.apply();
}
public void renameCustomListFile(long id, long destinationId)
{
FileReaderWriter frw = new FileReaderWriter(defaultPrefs.getString(
Constants.PREFS_PATH_BACKUP_DIRECTORY, FileCreationHelper
.getDefaultBackupDirPath()), SCHEDULECUSTOMLIST + id);
frw.rename(SCHEDULECUSTOMLIST + destinationId);
}
public void removeCustomListFile(long number)
{
FileReaderWriter frw = new FileReaderWriter(defaultPrefs.getString(
Constants.PREFS_PATH_BACKUP_DIRECTORY, FileCreationHelper
.getDefaultBackupDirPath()), SCHEDULECUSTOMLIST + number);
frw.delete();
}
// TODO: this class should ideally just implement Runnable but the
// confirmation dialog needs to accept those also
static class StartSchedule implements Utils.Command
{
private final WeakReference<Context> contextReference;
private final WeakReference<HandleScheduledBackups> handleScheduledBackupsReference;
private final long id;
private final String databasename;
private Optional<Thread> thread;
public StartSchedule(Context context, HandleScheduledBackups
handleScheduledBackups, long id, String databasename)
{
this.contextReference = new WeakReference<>(context);
// set the handlescheduledbackups object here to facilitate testing
this.handleScheduledBackupsReference = new WeakReference<>(
handleScheduledBackups);
this.id = id;
this.databasename = databasename;
}
public void execute()
{
final Thread t = new Thread(() -> {
final Context context = contextReference.get();
if(context != null) {
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(context, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
final Schedule schedule = scheduleDao.getSchedule(id);
final HandleScheduledBackups handleScheduledBackups =
handleScheduledBackupsReference.get();
if(handleScheduledBackups != null) {
handleScheduledBackups.initiateBackup((int) id,
schedule.getMode().getValue(), schedule.getSubmode()
.getValue() + 1, schedule.isExcludeSystem());
}
}
});
thread = Optional.of(t);
t.start();
}
// expose the thread for testing
Optional<Thread> getThread() {
return thread;
}
}
static class AddScheduleTask extends AsyncTask<Void, Void, ResultHolder<View>> {
// Use a weak reference to avoid leaking the activity if it's
// destroyed while this task is still running.
private final WeakReference<Scheduler> activityReference;
private final String databasename;
AddScheduleTask(Scheduler scheduler) {
activityReference = new WeakReference<>(scheduler);
databasename = DATABASE_NAME;
}
AddScheduleTask(Scheduler scheduler, String databasename) {
activityReference = new WeakReference<>(scheduler);
this.databasename = databasename;
}
@Override
public ResultHolder<View> doInBackground(Void... _void) {
final Scheduler scheduler = activityReference.get();
if(scheduler == null || scheduler.isFinishing()) {
return new ResultHolder<>();
}
return new ResultHolder<>(scheduler.buildUiForNewSchedule(
databasename));
}
@Override
public void onPostExecute(ResultHolder<View> resultHolder) {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
resultHolder.getObject().ifPresent(view -> {
scheduler.viewList.put((long)view.getTag(), view);
((LinearLayout) scheduler.findViewById(R.id.linearLayout))
.addView(view);
});
}
}
}
static class RemoveScheduleTask extends AsyncTask<Long, Void, ResultHolder<Long>> {
private final WeakReference<Scheduler> activityReference;
private final String databasename;
RemoveScheduleTask(Scheduler scheduler) {
activityReference = new WeakReference<>(scheduler);
databasename = DATABASE_NAME;
}
RemoveScheduleTask(Scheduler scheduler, String databasename) {
activityReference = new WeakReference<>(scheduler);
this.databasename = databasename;
}
@Override
public ResultHolder<Long> doInBackground(Long... ids) {
final Scheduler scheduler = activityReference.get();
if(scheduler == null || scheduler.isFinishing()) {
return new ResultHolder<>();
}
if(ids.length == 0) {
final IllegalStateException error =
new IllegalStateException(
"No id supplied to the schedule removing task");
return new ResultHolder<>(error);
}
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(scheduler, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
scheduleDao.deleteById(ids[0]);
return new ResultHolder<>(ids[0]);
}
@Override
public void onPostExecute(ResultHolder<Long> resultHolder) {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
resultHolder.getError().ifPresent(error -> {
final String message = String.format(
"Unable to remove schedule: %s", error.toString());
Log.e(TAG, message);
Toast.makeText(scheduler, message, Toast.LENGTH_LONG).show();
});
resultHolder.getObject().ifPresent(id -> {
final View view = scheduler.viewList.get(id);
scheduler.handleAlarms.cancelAlarm((int)(long)id);
scheduler.removeCustomListFile(id);
((LinearLayout) scheduler.findViewById(R.id.linearLayout))
.removeView(view);
scheduler.viewList.remove(id);
});
}
}
}
private static class UiLoaderTask extends AsyncTask<Void,
Void, ResultHolder<List<Schedule>>> {
private final WeakReference<Scheduler> activityReference;
UiLoaderTask(Scheduler scheduler) {
activityReference = new WeakReference<>(scheduler);
}
@Override
public ResultHolder<List<Schedule>> doInBackground(Void... _void) {
final Scheduler scheduler = activityReference.get();
if(scheduler == null || scheduler.isFinishing()) {
return new ResultHolder<>();
}
final SharedPreferences preferences = scheduler
.getSharedPreferences(Constants.PREFS_SCHEDULES, 0);
if(preferences.contains(Constants.PREFS_SCHEDULES_TOTAL)) {
scheduler.totalSchedules = preferences.getInt(
Constants.PREFS_SCHEDULES_TOTAL, 0);
// set to zero so there is always at least one schedule on activity start
scheduler.totalSchedules = scheduler.totalSchedules < 0 ?
0 : scheduler.totalSchedules;
try {
scheduler.migrateSchedulesToDatabase(preferences, DATABASE_NAME);
preferences.edit().remove(Constants.PREFS_SCHEDULES_TOTAL).apply();
} catch (SchedulingException e) {
return new ResultHolder<>(e);
}
}
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(scheduler, DATABASE_NAME);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
return new ResultHolder<>(scheduleDao.getAll());
}
@Override
public void onPostExecute(ResultHolder<List<Schedule>> resultHolder) {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
resultHolder.getError().ifPresent(error -> {
final String message = String.format(
"Unable to migrate schedules to database: %s",
error.toString());
Log.e(TAG, message);
Toast.makeText(scheduler, message, Toast.LENGTH_LONG).show();
});
resultHolder.getObject().ifPresent(scheduler::populateViews);
}
}
}
static class SystemExcludeCheckboxSetTask extends AsyncTask<Void, Void,
ResultHolder<Boolean>> {
private final WeakReference<Scheduler> activityReference;
private final WeakReference<CheckBox> checkBoxReference;
private final long id;
SystemExcludeCheckboxSetTask(Scheduler scheduler, long id, CheckBox checkBox) {
activityReference = new WeakReference<>(scheduler);
this.id = id;
this.checkBoxReference = new WeakReference<>(checkBox);
}
@Override
public ResultHolder<Boolean> doInBackground(Void... _void) {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(scheduler, DATABASE_NAME);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
final Schedule schedule = scheduleDao.getSchedule(id);
return new ResultHolder<>(schedule.isExcludeSystem());
}
return new ResultHolder<>();
}
@Override
public void onPostExecute(ResultHolder<Boolean> resultHolder) {
final Scheduler scheduler = activityReference.get();
final CheckBox checkBox = checkBoxReference.get();
if(scheduler != null && !scheduler.isFinishing() &&
checkBox != null) {
resultHolder.getObject().ifPresent(checkBox::setChecked);
}
}
}
private static class ResultHolder<T> {
private final Optional<T> object;
private final Optional<Throwable> error;
ResultHolder() {
object = Optional.empty();
error = Optional.empty();
}
ResultHolder(T object) {
this.object = Optional.of(object);
error = Optional.empty();
}
ResultHolder(Throwable error) {
this.error = Optional.of(error);
object = Optional.empty();
}
Optional<T> getObject() {
return object;
}
Optional<Throwable> getError() {
return error;
}
}
static class UpdateScheduleRunnable implements Runnable {
private final WeakReference<Scheduler> activityReference;
private final String databasename;
private final Schedule schedule;
public UpdateScheduleRunnable(Scheduler scheduler, String databasename,
Schedule schedule) {
this.activityReference = new WeakReference<>(scheduler);
this.databasename = databasename;
this.schedule = schedule;
}
@Override
public void run() {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(scheduler, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
scheduleDao.update(schedule);
}
}
}
static class ModeChangerRunnable implements Runnable {
private final WeakReference<Scheduler> activityReference;
private final long id;
private final Optional<Schedule.Mode> mode;
private final Optional<Schedule.Submode> submode;
private final String databasename;
ModeChangerRunnable(Scheduler scheduler, long id, Schedule.Mode mode) {
this(scheduler, id, mode, DATABASE_NAME);
}
ModeChangerRunnable(Scheduler scheduler, long id, Schedule.Submode submode) {
this(scheduler, id, submode, DATABASE_NAME);
}
ModeChangerRunnable(Scheduler scheduler, long id, Schedule.Mode mode,
String databasename) {
this.activityReference = new WeakReference<>(scheduler);
this.id = id;
this.mode = Optional.of(mode);
submode = Optional.empty();
this.databasename = databasename;
}
ModeChangerRunnable(Scheduler scheduler, long id, Schedule.Submode submode,
String databasename) {
this.activityReference = new WeakReference<>(scheduler);
this.id = id;
this.submode = Optional.of(submode);
mode = Optional.empty();
this.databasename = databasename;
}
@Override
public void run() {
final Scheduler scheduler = activityReference.get();
if(scheduler != null && !scheduler.isFinishing()) {
final ScheduleDatabase scheduleDatabase = ScheduleDatabaseHelper
.getScheduleDatabase(scheduler, databasename);
final ScheduleDao scheduleDao = scheduleDatabase.scheduleDao();
final Schedule schedule = scheduleDao.getSchedule(id);
if(schedule != null) {
mode.ifPresent(schedule::setMode);
submode.ifPresent(schedule::setSubmode);
scheduleDao.update(schedule);
} else {
final List<Schedule> schedules = scheduleDao.getAll();
Log.e(TAG, String.format(
"Unable to change mode for %s, couldn't get schedule " +
"from database. Persisted schedules: %s", id, schedules));
scheduler.runOnUiThread(() -> {
final String state = mode.isPresent() ?
"mode" : "submode";
Toast.makeText(scheduler, scheduler.getString(
R.string.error_updating_schedule_mode, state, id),
Toast.LENGTH_LONG).show();
});
}
}
}
}
}