proper handling of events in the background threads #128

This commit is contained in:
Angelo Fuchs
2018-11-20 11:51:24 +01:00
parent 50e22ddcc9
commit 7db7c5beeb
3 changed files with 18 additions and 21 deletions
+1 -19
View File
@@ -65,28 +65,10 @@ public class DcEventCenter {
if(observer.runOnMain()) {
Util.runOnMain(() -> observer.handleEvent(eventId, data1, data2));
} else {
new BackgroundEventHandler(observer, eventId)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, data1, data2);
Util.runOnBackground(() -> observer.handleEvent(eventId, data1, data2));
}
}
}
}
}
private static class BackgroundEventHandler extends AsyncTask<Object, Void, Void> {
private final WeakReference<DcEventDelegate> asyncDelegate;
private final int eventId;
BackgroundEventHandler(DcEventDelegate delegate, int eventId) {
asyncDelegate = new WeakReference<>(delegate);
this.eventId = eventId;
}
@Override
protected Void doInBackground(Object... data) {
DcEventDelegate delegate = asyncDelegate.get();
if(delegate != null) {
delegate.handleEvent(eventId, data[0], data[1]);
}
return null;
}
}
}
@@ -141,8 +141,10 @@ public class ApplicationContext extends MultiDexApplication implements Dependenc
});
// in five seconds, the system should be up and ready so we can start issuing notifications.
Util.runOnMainDelayed(() -> {
MessageNotifier.updateNotification(dcContext.context);}, 5000);
Util.runOnBackgroundDelayed(() -> {
MessageNotifier.updateNotification(dcContext.context);
}, 5000);
}
private void initializeJobManager() {
@@ -25,6 +25,7 @@ import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
@@ -39,6 +40,7 @@ import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.util.Log;
import com.google.android.exoplayer2.extractor.ts.PsExtractor;
import com.google.android.mms.pdu_alt.CharacterSets;
import com.google.android.mms.pdu_alt.EncodedStringValue;
@@ -52,6 +54,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.DecimalFormat;
@@ -381,6 +384,16 @@ public class Util {
}
}
public static void runOnBackground(final @NonNull Runnable runnable) {
AsyncTask.THREAD_POOL_EXECUTOR.execute(runnable);
}
public static void runOnBackgroundDelayed(final @NonNull Runnable runnable, long delayMillis) {
handler.postDelayed(() -> {
AsyncTask.THREAD_POOL_EXECUTOR.execute(runnable);
}, delayMillis);
}
public static <T> T getRandomElement(T[] elements) {
try {
return elements[SecureRandom.getInstance("SHA1PRNG").nextInt(elements.length)];