Merge branch '1142-wakeful-lifecycle' into 'master'

Hold a wake lock during app startup and shutdown

See merge request briar/briar!1271
This commit is contained in:
akwizgran
2020-08-13 15:33:09 +00:00
24 changed files with 281 additions and 144 deletions

View File

@@ -24,6 +24,7 @@ import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.plugin.PluginManager;
import org.briarproject.bramble.api.settings.SettingsManager;
import org.briarproject.bramble.api.system.AndroidExecutor;
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.api.system.LocationUtils;
import org.briarproject.bramble.plugin.tor.CircumventionProvider;
@@ -166,6 +167,8 @@ public interface AndroidComponent
FeatureFlags featureFlags();
AndroidWakeLockManager wakeLockManager();
void inject(SignInReminderReceiver briarService);
void inject(BriarService briarService);

View File

@@ -19,6 +19,7 @@ import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult;
import org.briarproject.bramble.api.system.AndroidExecutor;
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
import org.briarproject.briar.R;
import org.briarproject.briar.android.logout.HideUiActivity;
import org.briarproject.briar.api.android.AndroidNotificationManager;
@@ -48,6 +49,7 @@ import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.ALREADY_RUNNING;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.SUCCESS;
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
import static org.briarproject.briar.android.BriarApplication.ENTRY_ACTIVITY;
import static org.briarproject.briar.api.android.AndroidNotificationManager.FAILURE_CHANNEL_ID;
import static org.briarproject.briar.api.android.AndroidNotificationManager.FAILURE_NOTIFICATION_ID;
@@ -80,6 +82,8 @@ public class BriarService extends Service {
AccountManager accountManager;
@Inject
LockManager lockManager;
@Inject
AndroidWakeLockManager wakeLockManager;
// Fields that are accessed from background threads must be volatile
@Inject
@@ -108,54 +112,57 @@ public class BriarService extends Service {
return;
}
// Create notification channels
if (SDK_INT >= 26) {
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
NotificationChannel ongoingChannel = new NotificationChannel(
ONGOING_CHANNEL_ID,
getString(R.string.ongoing_notification_title),
IMPORTANCE_NONE);
ongoingChannel.setLockscreenVisibility(VISIBILITY_SECRET);
nm.createNotificationChannel(ongoingChannel);
NotificationChannel failureChannel = new NotificationChannel(
FAILURE_CHANNEL_ID,
getString(R.string.startup_failed_notification_title),
IMPORTANCE_DEFAULT);
failureChannel.setLockscreenVisibility(VISIBILITY_SECRET);
nm.createNotificationChannel(failureChannel);
}
Notification foregroundNotification =
notificationManager.getForegroundNotification();
startForeground(ONGOING_NOTIFICATION_ID, foregroundNotification);
// Start the services in a background thread
new Thread(() -> {
StartResult result = lifecycleManager.startServices(dbKey);
if (result == SUCCESS) {
started = true;
} else if (result == ALREADY_RUNNING) {
LOG.info("Already running");
stopSelf();
} else {
if (LOG.isLoggable(WARNING))
LOG.warning("Startup failed: " + result);
showStartupFailureNotification(result);
stopSelf();
// Hold a wake lock during startup
wakeLockManager.runWakefully(() -> {
// Create notification channels
if (SDK_INT >= 26) {
NotificationManager nm = (NotificationManager)
requireNonNull(getSystemService(NOTIFICATION_SERVICE));
NotificationChannel ongoingChannel = new NotificationChannel(
ONGOING_CHANNEL_ID,
getString(R.string.ongoing_notification_title),
IMPORTANCE_NONE);
ongoingChannel.setLockscreenVisibility(VISIBILITY_SECRET);
nm.createNotificationChannel(ongoingChannel);
NotificationChannel failureChannel = new NotificationChannel(
FAILURE_CHANNEL_ID,
getString(R.string.startup_failed_notification_title),
IMPORTANCE_DEFAULT);
failureChannel.setLockscreenVisibility(VISIBILITY_SECRET);
nm.createNotificationChannel(failureChannel);
}
}).start();
// Register for device shutdown broadcasts
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LOG.info("Device is shutting down");
shutdownFromBackground();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_SHUTDOWN);
filter.addAction("android.intent.action.QUICKBOOT_POWEROFF");
filter.addAction("com.htc.intent.action.QUICKBOOT_POWEROFF");
registerReceiver(receiver, filter);
Notification foregroundNotification =
notificationManager.getForegroundNotification();
startForeground(ONGOING_NOTIFICATION_ID, foregroundNotification);
// Start the services in a background thread
wakeLockManager.executeWakefully(() -> {
StartResult result = lifecycleManager.startServices(dbKey);
if (result == SUCCESS) {
started = true;
} else if (result == ALREADY_RUNNING) {
LOG.info("Already running");
stopSelf();
} else {
if (LOG.isLoggable(WARNING))
LOG.warning("Startup failed: " + result);
showStartupFailureNotification(result);
stopSelf();
}
}, "LifecycleStartup");
// Register for device shutdown broadcasts
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LOG.info("Device is shutting down");
shutdownFromBackground();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_SHUTDOWN);
filter.addAction("android.intent.action.QUICKBOOT_POWEROFF");
filter.addAction("com.htc.intent.action.QUICKBOOT_POWEROFF");
registerReceiver(receiver, filter);
}, "LifecycleStartup");
}
@Override
@@ -179,8 +186,8 @@ public class BriarService extends Service {
i.putExtra(EXTRA_NOTIFICATION_ID, FAILURE_NOTIFICATION_ID);
b.setContentIntent(PendingIntent.getActivity(BriarService.this,
0, i, FLAG_UPDATE_CURRENT));
Object o = getSystemService(NOTIFICATION_SERVICE);
NotificationManager nm = (NotificationManager) o;
NotificationManager nm = (NotificationManager)
requireNonNull(getSystemService(NOTIFICATION_SERVICE));
nm.notify(FAILURE_NOTIFICATION_ID, b.build());
// Bring the dashboard to the front to clear the back stack
i = new Intent(BriarService.this, ENTRY_ACTIVITY);
@@ -205,14 +212,17 @@ public class BriarService extends Service {
@Override
public void onDestroy() {
super.onDestroy();
LOG.info("Destroyed");
stopForeground(true);
if (receiver != null) unregisterReceiver(receiver);
// Stop the services in a background thread
new Thread(() -> {
if (started) lifecycleManager.stopServices();
}).start();
// Hold a wake lock during shutdown
wakeLockManager.runWakefully(() -> {
super.onDestroy();
LOG.info("Destroyed");
stopForeground(true);
if (receiver != null) unregisterReceiver(receiver);
// Stop the services in a background thread
wakeLockManager.executeWakefully(() -> {
if (started) lifecycleManager.stopServices();
}, "LifecycleShutdown");
}, "LifecycleShutdown");
}
@Override
@@ -257,20 +267,23 @@ public class BriarService extends Service {
}
private void shutdownFromBackground() {
// Stop the service
stopSelf();
// Hide the UI
hideUi();
// Wait for shutdown to complete, then exit
new Thread(() -> {
try {
if (started) lifecycleManager.waitForShutdown();
} catch (InterruptedException e) {
LOG.info("Interrupted while waiting for shutdown");
}
LOG.info("Exiting");
System.exit(0);
}).start();
// Hold a wake lock during shutdown
wakeLockManager.runWakefully(() -> {
// Stop the service
stopSelf();
// Hide the UI
hideUi();
// Wait for shutdown to complete, then exit
wakeLockManager.executeWakefully(() -> {
try {
if (started) lifecycleManager.waitForShutdown();
} catch (InterruptedException e) {
LOG.info("Interrupted while waiting for shutdown");
}
LOG.info("Exiting");
System.exit(0);
}, "BackgroundShutdown");
}, "BackgroundShutdown");
}
/**

View File

@@ -82,13 +82,19 @@ import org.briarproject.briar.android.test.TestDataActivity;
import dagger.Component;
@ActivityScope
@Component(
modules = {ActivityModule.class, ForumModule.class, SharingModule.class,
BlogModule.class, ContactModule.class, GroupListModule.class,
CreateGroupModule.class, GroupInvitationModule.class,
GroupConversationModule.class, GroupMemberModule.class,
GroupRevealModule.class},
dependencies = AndroidComponent.class)
@Component(modules = {
ActivityModule.class,
BlogModule.class,
ContactModule.class,
CreateGroupModule.class,
ForumModule.class,
GroupInvitationModule.class,
GroupConversationModule.class,
GroupListModule.class,
GroupMemberModule.class,
GroupRevealModule.class,
SharingModule.class
}, dependencies = AndroidComponent.class)
public interface ActivityComponent {
Activity activity();

View File

@@ -7,6 +7,8 @@ import android.widget.CheckBox;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
import org.briarproject.bramble.api.system.Wakeful;
import org.briarproject.briar.R;
import org.briarproject.briar.android.account.UnlockActivity;
import org.briarproject.briar.android.controller.BriarController;
@@ -32,6 +34,7 @@ import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION;
import static android.os.Build.VERSION.SDK_INT;
import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_DOZE_WHITELISTING;
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_PASSWORD;
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_UNLOCK;
@@ -47,7 +50,7 @@ public abstract class BriarActivity extends BaseActivity {
public static final String GROUP_NAME = "briar.GROUP_NAME";
private static final Logger LOG =
Logger.getLogger(BriarActivity.class.getName());
getLogger(BriarActivity.class.getName());
@Inject
BriarController briarController;
@@ -56,6 +59,8 @@ public abstract class BriarActivity extends BaseActivity {
DbController dbController;
@Inject
protected LockManager lockManager;
@Inject
AndroidWakeLockManager wakeLockManager;
@Override
public void onStart() {
@@ -130,6 +135,7 @@ public abstract class BriarActivity extends BaseActivity {
/**
* Sets the transition animations.
*
* @param enterTransition used to move views into initial positions
* @param exitTransition used to move views out when starting a <b>new</b> activity.
* @param returnTransition used when window is closing, because the activity is finishing.
@@ -197,22 +203,30 @@ public abstract class BriarActivity extends BaseActivity {
protected void signOut(boolean removeFromRecentApps,
boolean deleteAccount) {
if (briarController.accountSignedIn()) {
// Don't use UiResultHandler because we want the result even if
// this activity has been destroyed
briarController.signOut(result -> runOnUiThread(
() -> exit(removeFromRecentApps)), deleteAccount);
} else {
if (deleteAccount) briarController.deleteAccount();
exit(removeFromRecentApps);
}
// Hold a wake lock to ensure we exit before the device goes to sleep
wakeLockManager.runWakefully(() -> {
if (briarController.accountSignedIn()) {
// Don't use UiResultHandler because we want the result even if
// this activity has been destroyed
briarController.signOut(result -> {
Runnable exit = () -> exit(removeFromRecentApps);
wakeLockManager.executeWakefully(exit,
this::runOnUiThread, "SignOut");
}, deleteAccount);
} else {
if (deleteAccount) briarController.deleteAccount();
exit(removeFromRecentApps);
}
}, "SignOut");
}
@Wakeful
private void exit(boolean removeFromRecentApps) {
if (removeFromRecentApps) startExitActivity();
else finishAndExit();
}
@Wakeful
private void startExitActivity() {
Intent i = new Intent(this, ExitActivity.class);
i.addFlags(FLAG_ACTIVITY_NEW_TASK
@@ -222,6 +236,7 @@ public abstract class BriarActivity extends BaseActivity {
startActivity(i);
}
@Wakeful
private void finishAndExit() {
if (SDK_INT >= 21) finishAndRemoveTask();
else supportFinishAfterTransition();

View File

@@ -1,7 +1,10 @@
package org.briarproject.briar.android.controller;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.Wakeful;
import org.briarproject.briar.android.controller.handler.ResultHandler;
@NotNullByDefault
public interface BriarController extends ActivityLifecycleController {
void startAndBindService();
@@ -16,7 +19,8 @@ public interface BriarController extends ActivityLifecycleController {
void doNotAskAgainForDozeWhiteListing();
void signOut(ResultHandler<Void> eventHandler, boolean deleteAccount);
@Wakeful
void signOut(ResultHandler<Void> handler, boolean deleteAccount);
void deleteAccount();

View File

@@ -8,8 +8,10 @@ import org.briarproject.bramble.api.account.AccountManager;
import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.settings.Settings;
import org.briarproject.bramble.api.settings.SettingsManager;
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
import org.briarproject.briar.android.BriarService;
import org.briarproject.briar.android.BriarService.BriarServiceConnection;
import org.briarproject.briar.android.controller.handler.ResultHandler;
@@ -23,15 +25,17 @@ import javax.inject.Inject;
import androidx.annotation.CallSuper;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STARTING_SERVICES;
import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.briar.android.settings.SettingsFragment.SETTINGS_NAMESPACE;
import static org.briarproject.briar.android.util.UiUtils.needsDozeWhitelisting;
@NotNullByDefault
public class BriarControllerImpl implements BriarController {
private static final Logger LOG =
Logger.getLogger(BriarControllerImpl.class.getName());
getLogger(BriarControllerImpl.class.getName());
public static final String DOZE_ASK_AGAIN = "dozeAskAgain";
@@ -41,6 +45,7 @@ public class BriarControllerImpl implements BriarController {
private final Executor databaseExecutor;
private final SettingsManager settingsManager;
private final DozeWatchdog dozeWatchdog;
private final AndroidWakeLockManager wakeLockManager;
private final Activity activity;
private boolean bound = false;
@@ -50,7 +55,9 @@ public class BriarControllerImpl implements BriarController {
AccountManager accountManager,
LifecycleManager lifecycleManager,
@DatabaseExecutor Executor databaseExecutor,
SettingsManager settingsManager, DozeWatchdog dozeWatchdog,
SettingsManager settingsManager,
DozeWatchdog dozeWatchdog,
AndroidWakeLockManager wakeLockManager,
Activity activity) {
this.serviceConnection = serviceConnection;
this.accountManager = accountManager;
@@ -58,6 +65,7 @@ public class BriarControllerImpl implements BriarController {
this.databaseExecutor = databaseExecutor;
this.settingsManager = settingsManager;
this.dozeWatchdog = dozeWatchdog;
this.wakeLockManager = wakeLockManager;
this.activity = activity;
}
@@ -127,9 +135,8 @@ public class BriarControllerImpl implements BriarController {
}
@Override
public void signOut(ResultHandler<Void> eventHandler,
boolean deleteAccount) {
new Thread(() -> {
public void signOut(ResultHandler<Void> handler, boolean deleteAccount) {
wakeLockManager.executeWakefully(() -> {
try {
// Wait for the service to finish starting up
IBinder binder = serviceConnection.waitForBinder();
@@ -145,8 +152,8 @@ public class BriarControllerImpl implements BriarController {
} finally {
if (deleteAccount) accountManager.deleteAccount();
}
eventHandler.onResult(null);
}).start();
handler.onResult(null);
}, "SignOut");
}
@Override

View File

@@ -4,17 +4,14 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.system.AndroidExecutor;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BriarActivity;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.preference.PreferenceManager;
import info.guardianproject.GuardianProjectRSA4096;
@@ -23,6 +20,7 @@ import info.guardianproject.panic.PanicResponder;
import info.guardianproject.trustedintents.TrustedIntents;
import static android.os.Build.VERSION.SDK_INT;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.briar.android.panic.PanicPreferencesFragment.KEY_LOCK;
import static org.briarproject.briar.android.panic.PanicPreferencesFragment.KEY_PURGE;
@@ -31,12 +29,7 @@ import static org.briarproject.briar.android.panic.PanicPreferencesFragment.KEY_
public class PanicResponderActivity extends BriarActivity {
private static final Logger LOG =
Logger.getLogger(PanicResponderActivity.class.getName());
@Inject
protected LifecycleManager lifecycleManager;
@Inject
protected AndroidExecutor androidExecutor;
getLogger(PanicResponderActivity.class.getName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
@@ -63,13 +56,20 @@ public class PanicResponderActivity extends BriarActivity {
// Performing panic responses
if (sharedPref.getBoolean(KEY_PURGE, false)) {
LOG.info("Purging all data...");
deleteAllData();
signOut(true, true);
} else if (sharedPref.getBoolean(KEY_LOCK, true)) {
LOG.info("Signing out...");
signOut(true, false);
} else {
LOG.info("Configured not to purge or lock");
}
}
// non-destructive actions are allowed by non-connected trusted apps
if (sharedPref.getBoolean(KEY_LOCK, true)) {
} else if (sharedPref.getBoolean(KEY_LOCK, true)) {
// non-destructive actions are allowed by non-connected
// trusted apps
LOG.info("Signing out...");
signOut(true, false);
} else {
LOG.info("Configured not to lock");
}
}
}
@@ -85,11 +85,4 @@ public class PanicResponderActivity extends BriarActivity {
public void injectActivity(ActivityComponent component) {
component.inject(this);
}
private void deleteAllData() {
androidExecutor.runOnBackgroundThread(() -> {
LOG.info("Signing out...");
signOut(true, true);
});
}
}