Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

[shared_preferences] replace AsyncTask by Executor and Guava Future #3520

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/shared_preferences/shared_preferences/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.5.13+3

* Android: replace [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask) (was deprecated in API level 30) by [Executor](https://developer.android.com/reference/java/util/concurrent/Executor)

## 0.5.13+2

* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ android {
disable 'InvalidPackage'
}
}

dependencies {
implementation 'com.google.guava:guava:28.1-android'
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.io.ByteArrayInputStream;
Expand All @@ -21,6 +28,9 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Implementation of the {@link MethodChannel.MethodCallHandler} for the plugin. It is also
Expand All @@ -30,24 +40,34 @@
class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {

private static final String SHARED_PREFERENCES_NAME = "FlutterSharedPreferences";
private static final String SHARED_PREFERENCES_ERROR_CODE = "shared-preferences-error";

// Fun fact: The following is a base64 encoding of the string "This is the prefix for a list."
private static final String LIST_IDENTIFIER = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu";
private static final String BIG_INTEGER_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy";
private static final String DOUBLE_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu";

private final android.content.SharedPreferences preferences;
private final ExecutorService executor;
private final Executor uiThreadExecutor;

/**
* Constructs a {@link MethodCallHandlerImpl} instance. Creates a {@link
* android.content.SharedPreferences} based on the {@code context}.
*/
MethodCallHandlerImpl(Context context) {
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
executor =
Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder()
.setNameFormat("shared-preferences-background-%d")
.setPriority(Thread.NORM_PRIORITY)
.build());
uiThreadExecutor = new UiThreadExecutor();
}

@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
public void onMethodCall(MethodCall call, @NonNull MethodChannel.Result result) {
String key = call.argument("key");
try {
switch (call.method) {
Expand Down Expand Up @@ -118,17 +138,42 @@ public void onMethodCall(MethodCall call, MethodChannel.Result result) {

private void commitAsync(
final SharedPreferences.Editor editor, final MethodChannel.Result result) {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... voids) {
return editor.commit();
}
if (executor.isShutdown()) {
return;
}

@Override
protected void onPostExecute(Boolean value) {
result.success(value);
}
}.execute();
final SettableFuture<Boolean> future = SettableFuture.create();

Futures.addCallback(
future,
new FutureCallback<Boolean>() {
@Override
public void onSuccess(@Nullable Boolean b) {
if (b != null) {
result.success(b);
} else {
result.error(SHARED_PREFERENCES_ERROR_CODE, "Null result", null);
}
}

@Override
public void onFailure(@NonNull Throwable t) {
result.error(SHARED_PREFERENCES_ERROR_CODE, t.getMessage(), null);
}
},
uiThreadExecutor);

executor.execute(
new Runnable() {
@Override
public void run() {
try {
future.set(editor.commit());
} catch (Throwable t) {
future.setException(t);
}
}
});
}

private List<String> decodeList(String encodedList) throws IOException {
Expand Down Expand Up @@ -200,4 +245,17 @@ private Map<String, Object> getAllPrefs() throws IOException {
}
return filteredPrefs;
}

void teardown() {
executor.shutdown();
}

private static class UiThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());

@Override
public void execute(Runnable command) {
handler.post(command);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
public class SharedPreferencesPlugin implements FlutterPlugin {
private static final String CHANNEL_NAME = "plugins.flutter.io/shared_preferences";
private MethodChannel channel;
private MethodCallHandlerImpl handler;

@SuppressWarnings("deprecation")
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
Expand All @@ -32,11 +33,12 @@ public void onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding binding) {

private void setupChannel(BinaryMessenger messenger, Context context) {
channel = new MethodChannel(messenger, CHANNEL_NAME);
MethodCallHandlerImpl handler = new MethodCallHandlerImpl(context);
handler = new MethodCallHandlerImpl(context);
channel.setMethodCallHandler(handler);
}

private void teardownChannel() {
handler.teardown();
channel.setMethodCallHandler(null);
channel = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ homepage: https://github.com/flutter/plugins/tree/master/packages/shared_prefere
# 0.5.y+z is compatible with 1.0.0, if you land a breaking change bump
# the version to 2.0.0.
# See more details: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0
version: 0.5.13+2
version: 0.5.13+3

flutter:
plugin:
Expand Down