Merge pull request #1504 from deltachat/imex_foregroundservice

generic foregroundservice
This commit is contained in:
bjoern
2020-09-03 18:30:27 +02:00
committed by GitHub
7 changed files with 398 additions and 12 deletions
+2
View File
@@ -285,6 +285,8 @@
</intent-filter>
</service>
<service android:name=".service.GenericForegroundService" />
<receiver android:name=".notifications.MarkReadReceiver"
android:enabled="true"
android:exported="false">
@@ -5,11 +5,12 @@ import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import com.b44t.messenger.DcContext;
import com.b44t.messenger.DcEventCenter;
import com.b44t.messenger.DcLot;
@@ -21,6 +22,8 @@ import org.thoughtcrime.securesms.connect.ApplicationDcContext;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.permissions.Permissions;
import org.thoughtcrime.securesms.qr.RegistrationQrActivity;
import org.thoughtcrime.securesms.service.GenericForegroundService;
import org.thoughtcrime.securesms.service.NotificationController;
import org.thoughtcrime.securesms.util.views.ProgressDialog;
import java.io.File;
@@ -31,6 +34,7 @@ public class WelcomeActivity extends BaseActionBarActivity implements DcEventCen
private boolean manualConfigure = true; // false: configure by QR account creation
private ProgressDialog progressDialog = null;
ApplicationDcContext dcContext;
private NotificationController notificationController;
@Override
public void onCreate(Bundle bundle) {
@@ -116,6 +120,7 @@ public class WelcomeActivity extends BaseActionBarActivity implements DcEventCen
private void startImport(final String backupFile)
{
notificationController = GenericForegroundService.startForegroundTask(this, getString(R.string.import_backup_title));
if( progressDialog!=null ) {
progressDialog.dismiss();
progressDialog = null;
@@ -189,7 +194,6 @@ public class WelcomeActivity extends BaseActionBarActivity implements DcEventCen
} else {
startActivity(new Intent(getApplicationContext(), ConversationListActivity.class));
}
finish();
}
@@ -199,13 +203,16 @@ public class WelcomeActivity extends BaseActionBarActivity implements DcEventCen
long progress = (Long)data1;
if (progress==0/*error/aborted*/) {
progressError();
notificationController.close();
}
else if (progress<1000/*progress in permille*/) {
progressUpdate((int)progress);
notificationController.setProgress(1000, progress, String.format(" %d%%", (int) progress / 10));
}
else if (progress==1000/*done*/) {
dcContext.maybeStartIo();
progressSuccess(false);
notificationController.close();
}
}
else if (manualConfigure && eventId==DcContext.DC_EVENT_CONFIGURE_PROGRESS) {
@@ -11,6 +11,8 @@ import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import org.thoughtcrime.securesms.ConversationListActivity;
@@ -34,14 +36,7 @@ public class KeepAliveService extends Service {
public static void startSelf(Context context)
{
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// the started service has to call startForeground() within 5 seconds,
// see https://developer.android.com/about/versions/oreo/android-8.0-changes
context.startForegroundService(new Intent(context, KeepAliveService.class));
}
else {
context.startService(new Intent(context, KeepAliveService.class));
}
ContextCompat.startForegroundService(context, new Intent(context, KeepAliveService.class));
}
catch(Exception e) {
e.printStackTrace();
@@ -173,6 +173,7 @@ public class NotificationCenter {
public static final String CH_MSG_PREFIX = "ch_msg";
public static final String CH_MSG_VERSION = "4";
public static final String CH_PERMANENT = "dc_foreground_notification_ch";
public static final String CH_GENERIC = "ch_generic";
private boolean notificationChannelsSupported() {
return Build.VERSION.SDK_INT >= 26;
@@ -3,6 +3,7 @@ package org.thoughtcrime.securesms.preferences;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
@@ -13,6 +14,8 @@ import com.b44t.messenger.DcEventCenter;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.connect.ApplicationDcContext;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.service.GenericForegroundService;
import org.thoughtcrime.securesms.service.NotificationController;
import org.thoughtcrime.securesms.util.ScreenLockUtil;
import org.thoughtcrime.securesms.util.views.ProgressDialog;
@@ -22,6 +25,7 @@ public abstract class ListSummaryPreferenceFragment extends CorrectedPreferenceF
protected static final int REQUEST_CODE_CONFIRM_CREDENTIALS_BACKUP = ScreenLockUtil.REQUEST_CODE_CONFIRM_CREDENTIALS + 1;
protected static final int REQUEST_CODE_CONFIRM_CREDENTIALS_KEYS = REQUEST_CODE_CONFIRM_CREDENTIALS_BACKUP + 1;
protected ApplicationDcContext dcContext;
private NotificationController notificationController;
@Override
public void onCreate(Bundle icicle) {
@@ -66,6 +70,7 @@ public abstract class ListSummaryPreferenceFragment extends CorrectedPreferenceF
protected String imexDir = "";
protected void startImex(int what)
{
notificationController = GenericForegroundService.startForegroundTask(getContext(), getString(R.string.export_backup_desktop));
if( progressDialog!=null ) {
progressDialog.dismiss();
progressDialog = null;
@@ -97,15 +102,19 @@ public abstract class ListSummaryPreferenceFragment extends CorrectedPreferenceF
.setPositiveButton(android.R.string.ok, null)
.show();
}
notificationController.close();
}
else if (progress<1000/*progress in permille*/) {
int percent = (int)progress / 10;
progressDialog.setMessage(getResources().getString(R.string.one_moment)+String.format(" %d%%", percent));
String formattedPercent = String.format(" %d%%", percent);
progressDialog.setMessage(getResources().getString(R.string.one_moment) + formattedPercent);
notificationController.setProgress(1000, progress, formattedPercent);
}
else if (progress==1000/*done*/) {
dcContext.endCaptureNextError();
progressDialog.dismiss();
progressDialog = null;
notificationController.close();
String msg = "";
if (progressWhat==DcContext.DC_IMEX_EXPORT_BACKUP) {
msg = getActivity().getString(R.string.pref_backup_written_to_x, imexDir);
@@ -0,0 +1,276 @@
package org.thoughtcrime.securesms.service;
import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat.Builder;
import androidx.core.content.ContextCompat;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.notifications.NotificationCenter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public final class GenericForegroundService extends Service {
private static final String TAG = GenericForegroundService.class.getSimpleName();
private final IBinder binder = new LocalBinder();
private static final int NOTIFICATION_ID = 849319618;
private static final String EXTRA_TITLE = "extra_title";
private static final String EXTRA_CONTENT_TEXT = "extra_content_text";
private static final String EXTRA_CHANNEL_ID = "extra_channel_id";
private static final String EXTRA_ICON_RES = "extra_icon_res";
private static final String EXTRA_ID = "extra_id";
private static final String EXTRA_PROGRESS = "extra_progress";
private static final String EXTRA_PROGRESS_MAX = "extra_progress_max";
private static final String EXTRA_PROGRESS_INDETERMINATE = "extra_progress_indeterminate";
private static final String ACTION_START = "start";
private static final String ACTION_STOP = "stop";
private static final AtomicInteger NEXT_ID = new AtomicInteger();
private static final AtomicBoolean CHANNEL_CREATED = new AtomicBoolean(false);
private final LinkedHashMap<Integer, Entry> allActiveMessages = new LinkedHashMap<>();
private static final Entry DEFAULTS = new Entry("", "", NotificationCenter.CH_GENERIC, R.drawable.icon_notification, -1, 0, 0, false);
private @Nullable Entry lastPosted;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
throw new IllegalStateException("Intent needs to be non-null.");
}
synchronized (GenericForegroundService.class) {
String action = intent.getAction();
if (ACTION_START.equals(action)) handleStart(intent);
else if (ACTION_STOP .equals(action)) handleStop(intent);
else throw new IllegalStateException(String.format("Action needs to be %s or %s.", ACTION_START, ACTION_STOP));
updateNotification();
return START_NOT_STICKY;
}
}
private synchronized void updateNotification() {
Iterator<Entry> iterator = allActiveMessages.values().iterator();
if (iterator.hasNext()) {
postObligatoryForegroundNotification(iterator.next());
} else {
Log.i(TAG, "Last request. Ending foreground service.");
postObligatoryForegroundNotification(lastPosted != null ? lastPosted : DEFAULTS);
stopForeground(true);
stopSelf();
}
}
private synchronized void handleStart(@NonNull Intent intent) {
Entry entry = Entry.fromIntent(intent);
Log.i(TAG, String.format(Locale.US, "handleStart() %s", entry));
allActiveMessages.put(entry.id, entry);
}
private synchronized void handleStop(@NonNull Intent intent) {
Log.i(TAG, "handleStop()");
int id = intent.getIntExtra(EXTRA_ID, -1);
Entry removed = allActiveMessages.remove(id);
if (removed == null) {
Log.w(TAG, "Could not find entry to remove");
}
}
private void postObligatoryForegroundNotification(@NonNull Entry active) {
lastPosted = active;
startForeground(NOTIFICATION_ID, new Builder(this, active.channelId)
.setSmallIcon(active.iconRes)
.setContentTitle(active.title)
.setTicker(active.contentText)
.setContentText(active.contentText)
.setProgress(active.progressMax, active.progress, active.indeterminate)
.build());
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public static NotificationController startForegroundTask(@NonNull Context context, @NonNull String task) {
final int id = NEXT_ID.getAndIncrement();
createFgNotificationChannel(context);
Intent intent = new Intent(context, GenericForegroundService.class);
intent.setAction(ACTION_START);
intent.putExtra(EXTRA_TITLE, task);
intent.putExtra(EXTRA_CHANNEL_ID, NotificationCenter.CH_GENERIC);
intent.putExtra(EXTRA_ICON_RES, R.drawable.notification_permanent);
intent.putExtra(EXTRA_ID, id);
ContextCompat.startForegroundService(context, intent);
return new NotificationController(context, id);
}
public static void stopForegroundTask(@NonNull Context context, int id) {
Intent intent = new Intent(context, GenericForegroundService.class);
intent.setAction(ACTION_STOP);
intent.putExtra(EXTRA_ID, id);
ContextCompat.startForegroundService(context, intent);
}
synchronized void replaceProgress(int id, int progressMax, int progress, boolean indeterminate, String message) {
Entry oldEntry = allActiveMessages.get(id);
if (oldEntry == null) {
Log.w(TAG, "Failed to replace notification, it was not found");
return;
}
if (message == null) {
message = oldEntry.contentText;
}
Entry newEntry = new Entry(oldEntry.title, message, oldEntry.channelId, oldEntry.iconRes, oldEntry.id, progressMax, progress, indeterminate);
if (oldEntry.equals(newEntry)) {
Log.d(TAG, String.format("handleReplace() skip, no change %s", newEntry));
return;
}
Log.i(TAG, String.format("handleReplace() %s", newEntry));
allActiveMessages.put(newEntry.id, newEntry);
updateNotification();
}
@TargetApi(Build.VERSION_CODES.O)
static private void createFgNotificationChannel(Context context) {
if(!CHANNEL_CREATED.get() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CHANNEL_CREATED.set(true);
NotificationChannel channel = new NotificationChannel(NotificationCenter.CH_GENERIC,
"Generic Background Service", NotificationManager.IMPORTANCE_MIN);
channel.setDescription("Ensure app will not be killed while long ongoing background tasks are running.");
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private static class Entry {
final @NonNull String title;
final @NonNull String contentText;
final @NonNull String channelId;
final int id;
final @DrawableRes int iconRes;
final int progress;
final int progressMax;
final boolean indeterminate;
private Entry(@NonNull String title, @NonNull String contentText, @NonNull String channelId, @DrawableRes int iconRes, int id, int progressMax, int progress, boolean indeterminate) {
this.title = title;
this.contentText = contentText;
this.channelId = channelId;
this.iconRes = iconRes;
this.id = id;
this.progress = progress;
this.progressMax = progressMax;
this.indeterminate = indeterminate;
}
private static Entry fromIntent(@NonNull Intent intent) {
int id = intent.getIntExtra(EXTRA_ID, DEFAULTS.id);
String title = intent.getStringExtra(EXTRA_TITLE);
if (title == null) title = DEFAULTS.title;
String contentText = intent.getStringExtra(EXTRA_CONTENT_TEXT);
if (contentText == null) contentText = DEFAULTS.contentText;
String channelId = intent.getStringExtra(EXTRA_CHANNEL_ID);
if (channelId == null) channelId = DEFAULTS.channelId;
int iconRes = intent.getIntExtra(EXTRA_ICON_RES, DEFAULTS.iconRes);
int progress = intent.getIntExtra(EXTRA_PROGRESS, DEFAULTS.progress);
int progressMax = intent.getIntExtra(EXTRA_PROGRESS_MAX, DEFAULTS.progressMax);
boolean indeterminate = intent.getBooleanExtra(EXTRA_PROGRESS_INDETERMINATE, DEFAULTS.indeterminate);
return new Entry(title, contentText, channelId, iconRes, id, progressMax, progress, indeterminate);
}
@Override
public @NonNull String toString() {
return String.format(Locale.US, "ChannelId: %s Id: %d Progress: %d/%d %s", channelId, id, progress, progressMax, indeterminate ? "indeterminate" : "determinate");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
return id == entry.id &&
iconRes == entry.iconRes &&
progress == entry.progress &&
progressMax == entry.progressMax &&
indeterminate == entry.indeterminate &&
title.equals(entry.title) &&
channelId.equals(entry.channelId);
}
@Override
public int hashCode() {
int hashCode = title.hashCode();
hashCode *= 31;
hashCode += channelId.hashCode();
hashCode *= 31;
hashCode += id;
hashCode *= 31;
hashCode += iconRes;
hashCode *= 31;
hashCode += progress;
hashCode *= 31;
hashCode += progressMax;
hashCode *= 31;
hashCode += indeterminate ? 1 : 0;
return hashCode;
}
}
class LocalBinder extends Binder {
GenericForegroundService getService() {
// Return this instance of LocalService so clients can call public methods
return GenericForegroundService.this;
}
}
}
@@ -0,0 +1,96 @@
package org.thoughtcrime.securesms.service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.annotation.NonNull;
import java.util.concurrent.atomic.AtomicReference;
/**
* Class to control notifications triggered by GenericForeGroundService.
*
*/
public final class NotificationController {
private final @NonNull Context context;
private final int id;
private int progress;
private int progressMax;
private boolean indeterminate;
private String message = "";
private long percent = -1;
private final ServiceConnection serviceConnection;
private final AtomicReference<GenericForegroundService> service = new AtomicReference<>();
NotificationController(@NonNull Context context, int id) {
this.context = context;
this.id = id;
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
GenericForegroundService.LocalBinder binder = (GenericForegroundService.LocalBinder) service;
GenericForegroundService genericForegroundService = binder.getService();
NotificationController.this.service.set(genericForegroundService);
updateProgressOnService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
service.set(null);
}
};
context.bindService(new Intent(context, GenericForegroundService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}
public int getId() {
return id;
}
public void close() {
GenericForegroundService.stopForegroundTask(context, id);
context.unbindService(serviceConnection);
}
public void setIndeterminateProgress() {
setProgress(0, 0, true, message);
}
public void setProgress(long newProgressMax, long newProgress, @NonNull String newMessage) {
setProgress((int) newProgressMax, (int) newProgress, false, newMessage);
}
private synchronized void setProgress(int newProgressMax, int newProgress, boolean indeterminant, @NonNull String newMessage) {
int newPercent = newProgressMax != 0 ? 100 * newProgress / newProgressMax : -1;
boolean same = newPercent == percent && indeterminate == indeterminant && newMessage.equals(message);
percent = newPercent;
progress = newProgress;
progressMax = newProgressMax;
indeterminate = indeterminant;
message = newMessage;
if (same) return;
updateProgressOnService();
}
private synchronized void updateProgressOnService() {
GenericForegroundService genericForegroundService = service.get();
if (genericForegroundService == null) return;
genericForegroundService.replaceProgress(id, progressMax, progress, indeterminate, message);
}
}