Repository navigation
Expand file tree
/
Copy pathMailJobService.java
More file actions
70 lines (68 loc) · 3.04 KB
/
Copy pathMailJobService.java
File metadata and controls
70 lines (68 loc) · 3.04 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
package dev.makepad.octosense;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import org.json.JSONObject;
/** Network-constrained, bounded, quiet work. Never starts an Activity or FGS. */
public final class MailJobService extends JobService {
private final Handler main = new Handler(Looper.getMainLooper());
private Run current;
private static final class Run {
volatile boolean cancelled;
long lease;
}
@Override public boolean onStartJob(JobParameters params) {
if (current != null) return false;
Run run = new Run(); current = run;
new Thread(() -> {
long started = SystemClock.elapsedRealtime();
android.util.Log.i("OctoMail", "Background mail job started");
try {
if (!MailBackground.init(getApplicationContext())) return;
synchronized (run) {
if (run.cancelled) return;
run.lease = MailBackground.nativeBegin();
}
int ticks = 0;
while (!run.cancelled && SystemClock.elapsedRealtime()-started < 240000) {
boolean snapshot = ticks++ % 10 == 0;
JSONObject state = new JSONObject(MailBackground.nativeTick(snapshot));
if (snapshot && !state.has("error")) {
MailBackground.post(getApplicationContext(), state);
if (!state.optBoolean("enabled")) {
MailBackground.schedule(getApplicationContext(), false);
break;
}
// Rust accounts for every enabled worker and the exact
// lease start; an empty legacy Mail queue is insufficient.
if (state.optBoolean("job_complete")) break;
}
Thread.sleep(100);
}
} catch (Exception error) {
android.util.Log.w("OctoMail", "Background mail job incomplete; durable events retained");
} finally {
synchronized (run) { if (run.lease != 0) MailBackground.nativeEnd(run.lease); }
android.util.Log.i("OctoMail", "Background mail job ended");
main.post(() -> {
if (current == run) { current = null; if (!run.cancelled) jobFinished(params, false); }
});
}
}, "mail-job").start();
return true;
}
private void stopRun() {
Run run = current; current = null;
if (run != null) synchronized (run) {
run.cancelled = true;
if (run.lease != 0) MailBackground.nativeEnd(run.lease);
}
}
@Override public boolean onStopJob(JobParameters params) {
stopRun();
return false; // Keep the ordinary periodic schedule; no aggressive retry loop.
}
@Override public void onDestroy() { stopRun(); super.onDestroy(); }
}