Skip to content

Commit 3ec72ae

Browse files
xRossKohKenneth Koh
andauthored
Offload blocking work in ProcessTextPlugin to the background (flutter#189823)
This PR offloads the method handlers of the ProcessTextPlugin to a background TaskQueue. The offloading of the querying of text actions to a background thread moves the following transactions off the main thread: 1. Binder transaction of querying the package manager for activities with process text intent 2. Disk I/O transactions of resolving the text action labels from the APKs of the individual activities The above transactions occurring on the main thread is an anti-pattern according to https://developer.android.com/topic/performance/anrs/find-unresponsive-thread#common-causes Attached below is a Perfetto trace validating that the querying of text actions now occurs on a background thread. <img width="2258" height="135" alt="image" src="https://github.com/user-attachments/assets/f5122ded-9a0f-4978-afa9-82ca19324358" /> The processTextAction method handler is also moved to a background thread, with additional handling to ensure that the launching of the text action activity is delegated back to the main UI thread. Attached below is a Perfetto trace validating that the processing of a text action begins on a background thread but is later delegated back to the main thread to launch the activity. <img width="1982" height="170" alt="image" src="https://github.com/user-attachments/assets/a499377f-9543-4d26-87be-b346132ca472" /> Note that the above Perfetto traces have additional trace logging implemented to better visualize when the method handlers are called. This PR also refactors ProcessTextChannel to use `DartExecutor.getBinaryMessenger()` instead of using `DartExecutor` as the `BinaryMessenger` object directly, so that the deprecated wrapper methods of `BinaryMessenger` in `DartExecutor` are no longer used. https://github.com/flutter/flutter/blob/80cabc33032837357c9b233d693266b890860c12/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/dart/DartExecutor.java#L203-L264 The unit tests for ProcessTextPlugin have also been refactored as such and the obsolete tags to suppress deprecated warnings have also been cleaned up. Issue: flutter#189176 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md Co-authored-by: Kenneth Koh <[email protected]>
1 parent dcf1076 commit 3ec72ae

3 files changed

Lines changed: 70 additions & 37 deletions

File tree

‎engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/systemchannels/ProcessTextChannel.java‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import androidx.annotation.NonNull;
99
import androidx.annotation.Nullable;
1010
import io.flutter.embedding.engine.dart.DartExecutor;
11+
import io.flutter.plugin.common.BinaryMessenger;
1112
import io.flutter.plugin.common.MethodCall;
1213
import io.flutter.plugin.common.MethodChannel;
1314
import io.flutter.plugin.common.StandardMethodCodec;
@@ -87,7 +88,14 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result
8788
public ProcessTextChannel(
8889
@NonNull DartExecutor dartExecutor, @NonNull PackageManager packageManager) {
8990
this.packageManager = packageManager;
90-
channel = new MethodChannel(dartExecutor, CHANNEL_NAME, StandardMethodCodec.INSTANCE);
91+
BinaryMessenger.TaskQueue taskQueue =
92+
dartExecutor.getBinaryMessenger().makeBackgroundTaskQueue();
93+
channel =
94+
new MethodChannel(
95+
dartExecutor.getBinaryMessenger(),
96+
CHANNEL_NAME,
97+
StandardMethodCodec.INSTANCE,
98+
taskQueue);
9199
channel.setMethodCallHandler(parsingMethodHandler);
92100
}
93101

‎engine/src/flutter/shell/platform/android/io/flutter/plugin/text/ProcessTextPlugin.java‎

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
import android.content.pm.PackageManager;
1212
import android.content.pm.ResolveInfo;
1313
import android.os.Build;
14+
import android.os.Handler;
15+
import android.os.Looper;
1416
import androidx.annotation.NonNull;
1517
import androidx.annotation.Nullable;
1618
import io.flutter.embedding.engine.plugins.FlutterPlugin;
@@ -32,16 +34,22 @@ public class ProcessTextPlugin
3234

3335
@NonNull private final ProcessTextChannel processTextChannel;
3436
@NonNull private final PackageManager packageManager;
35-
@Nullable private ActivityPluginBinding activityBinding;
37+
@NonNull private final Handler mainThreadHandler;
38+
@Nullable private volatile ActivityPluginBinding activityBinding;
39+
// The use of a Map for this variable assumes that it is only accessed
40+
// serially on the background task queue.
3641
private Map<String, ResolveInfo> resolveInfosById;
3742

43+
// The use of a Map for this variable assumes that it is only accessed
44+
// serially on the main thread.
3845
@NonNull
3946
private Map<Integer, MethodChannel.Result> requestsByCode =
4047
new HashMap<Integer, MethodChannel.Result>();
4148

4249
public ProcessTextPlugin(@NonNull ProcessTextChannel processTextChannel) {
4350
this.processTextChannel = processTextChannel;
4451
this.packageManager = processTextChannel.packageManager;
52+
this.mainThreadHandler = new Handler(Looper.getMainLooper());
4553

4654
processTextChannel.setMethodHandler(this);
4755
}
@@ -81,20 +89,27 @@ public void processTextAction(
8189
return;
8290
}
8391

84-
Integer requestCode = result.hashCode();
85-
requestsByCode.put(requestCode, result);
86-
87-
Intent intent = new Intent();
88-
intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
89-
intent.setAction(Intent.ACTION_PROCESS_TEXT);
90-
intent.setType("text/plain");
91-
intent.putExtra(Intent.EXTRA_PROCESS_TEXT, text);
92-
intent.putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, readOnly);
93-
94-
// Start the text processing activity. When the activity completes, the onActivityResult
95-
// callback
96-
// is called.
97-
activityBinding.getActivity().startActivityForResult(intent, requestCode);
92+
mainThreadHandler.post(
93+
() -> {
94+
if (activityBinding == null) {
95+
result.error("error", "Plugin not bound to an Activity", null);
96+
return;
97+
}
98+
99+
final Integer requestCode = result.hashCode();
100+
requestsByCode.put(requestCode, result);
101+
102+
Intent intent = new Intent();
103+
intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
104+
intent.setAction(Intent.ACTION_PROCESS_TEXT);
105+
intent.setType("text/plain");
106+
intent.putExtra(Intent.EXTRA_PROCESS_TEXT, text);
107+
intent.putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, readOnly);
108+
109+
// Start the text processing activity. When the activity completes, the
110+
// onActivityResult callback is called.
111+
activityBinding.getActivity().startActivityForResult(intent, requestCode);
112+
});
98113
}
99114

100115
private void cacheResolveInfos() {

‎engine/src/flutter/shell/platform/android/test/io/flutter/plugin/text/ProcessTextPluginTest.java‎

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import static org.junit.Assert.assertEquals;
55
import static org.mockito.Mockito.any;
66
import static org.mockito.Mockito.anyInt;
7+
import static org.mockito.Mockito.doReturn;
78
import static org.mockito.Mockito.mock;
89
import static org.mockito.Mockito.times;
910
import static org.mockito.Mockito.verify;
@@ -34,6 +35,7 @@
3435
import org.junit.Test;
3536
import org.junit.runner.RunWith;
3637
import org.mockito.ArgumentCaptor;
38+
import org.robolectric.shadows.ShadowLooper;
3739

3840
@RunWith(AndroidJUnit4.class)
3941
@TargetApi(API_LEVELS.API_24)
@@ -48,18 +50,19 @@ private static void sendToBinaryMessageHandler(
4850
(ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class));
4951
}
5052

51-
@SuppressWarnings("deprecation")
52-
// setMessageHandler is deprecated.
5353
@Test
5454
public void respondsToProcessTextChannelMessage() {
5555
ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor =
5656
ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class);
57-
DartExecutor mockBinaryMessenger = mock(DartExecutor.class);
57+
DartExecutor mockDartExecutor = mock(DartExecutor.class);
58+
BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
59+
when(mockDartExecutor.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
60+
doReturn(null).when(mockBinaryMessenger).makeBackgroundTaskQueue();
5861
ProcessTextChannel.ProcessTextMethodHandler mockHandler =
5962
mock(ProcessTextChannel.ProcessTextMethodHandler.class);
6063
PackageManager mockPackageManager = mock(PackageManager.class);
6164
ProcessTextChannel processTextChannel =
62-
new ProcessTextChannel(mockBinaryMessenger, mockPackageManager);
65+
new ProcessTextChannel(mockDartExecutor, mockPackageManager);
6366

6467
processTextChannel.setMethodHandler(mockHandler);
6568

@@ -74,14 +77,15 @@ public void respondsToProcessTextChannelMessage() {
7477
verify(mockHandler).queryTextActions();
7578
}
7679

77-
@SuppressWarnings("deprecation")
78-
// setMessageHandler is deprecated.
7980
@Test
8081
public void performQueryTextActions() {
81-
DartExecutor mockBinaryMessenger = mock(DartExecutor.class);
82+
DartExecutor mockDartExecutor = mock(DartExecutor.class);
83+
BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
84+
when(mockDartExecutor.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
85+
doReturn(null).when(mockBinaryMessenger).makeBackgroundTaskQueue();
8286
PackageManager mockPackageManager = mock(PackageManager.class);
8387
ProcessTextChannel processTextChannel =
84-
new ProcessTextChannel(mockBinaryMessenger, mockPackageManager);
88+
new ProcessTextChannel(mockDartExecutor, mockPackageManager);
8589

8690
// Set up mocked result for PackageManager.queryIntentActivities.
8791
ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager);
@@ -100,14 +104,15 @@ public void performQueryTextActions() {
100104
assertEquals(textActions, Map.of(action1Id, "Action1", action2Id, "Action2"));
101105
}
102106

103-
@SuppressWarnings("deprecation")
104-
// setMessageHandler is deprecated.
105107
@Test
106108
public void performProcessTextActionWithNoReturnedValue() {
107-
DartExecutor mockBinaryMessenger = mock(DartExecutor.class);
109+
DartExecutor mockDartExecutor = mock(DartExecutor.class);
110+
BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
111+
when(mockDartExecutor.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
112+
doReturn(null).when(mockBinaryMessenger).makeBackgroundTaskQueue();
108113
PackageManager mockPackageManager = mock(PackageManager.class);
109114
ProcessTextChannel processTextChannel =
110-
new ProcessTextChannel(mockBinaryMessenger, mockPackageManager);
115+
new ProcessTextChannel(mockDartExecutor, mockPackageManager);
111116

112117
// Set up mocked result for PackageManager.queryIntentActivities.
113118
ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager);
@@ -130,10 +135,11 @@ public void performProcessTextActionWithNoReturnedValue() {
130135
when(mockActivityPluginBinding.getActivity()).thenReturn(mockActivity);
131136
processTextPlugin.onAttachedToActivity(mockActivityPluginBinding);
132137

133-
// Execute th first action.
138+
// Execute the first action.
134139
String textToBeProcessed = "Flutter!";
135140
MethodChannel.Result result = mock(MethodChannel.Result.class);
136141
processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result);
142+
ShadowLooper.runUiThreadTasks();
137143

138144
// Activity.startActivityForResult should have been called.
139145
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -149,14 +155,15 @@ public void performProcessTextActionWithNoReturnedValue() {
149155
verify(result).success(null);
150156
}
151157

152-
@SuppressWarnings("deprecation")
153-
// setMessageHandler is deprecated.
154158
@Test
155159
public void performProcessTextActionWithReturnedValue() {
156-
DartExecutor mockBinaryMessenger = mock(DartExecutor.class);
160+
DartExecutor mockDartExecutor = mock(DartExecutor.class);
161+
BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
162+
when(mockDartExecutor.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
163+
doReturn(null).when(mockBinaryMessenger).makeBackgroundTaskQueue();
157164
PackageManager mockPackageManager = mock(PackageManager.class);
158165
ProcessTextChannel processTextChannel =
159-
new ProcessTextChannel(mockBinaryMessenger, mockPackageManager);
166+
new ProcessTextChannel(mockDartExecutor, mockPackageManager);
160167

161168
// Set up mocked result for PackageManager.queryIntentActivities.
162169
ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager);
@@ -183,6 +190,7 @@ public void performProcessTextActionWithReturnedValue() {
183190
String textToBeProcessed = "Flutter!";
184191
MethodChannel.Result result = mock(MethodChannel.Result.class);
185192
processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result);
193+
ShadowLooper.runUiThreadTasks();
186194

187195
// Activity.startActivityForResult should have been called.
188196
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -200,14 +208,15 @@ public void performProcessTextActionWithReturnedValue() {
200208
verify(result).success(processedText);
201209
}
202210

203-
@SuppressWarnings("deprecation")
204-
// setMessageHandler is deprecated.
205211
@Test
206212
public void doNotCrashOnNonRelatedActivityResult() {
207-
DartExecutor mockBinaryMessenger = mock(DartExecutor.class);
213+
DartExecutor mockDartExecutor = mock(DartExecutor.class);
214+
BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
215+
when(mockDartExecutor.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
216+
doReturn(null).when(mockBinaryMessenger).makeBackgroundTaskQueue();
208217
PackageManager mockPackageManager = mock(PackageManager.class);
209218
ProcessTextChannel processTextChannel =
210-
new ProcessTextChannel(mockBinaryMessenger, mockPackageManager);
219+
new ProcessTextChannel(mockDartExecutor, mockPackageManager);
211220

212221
// Set up mocked result for PackageManager.queryIntentActivities.
213222
ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager);
@@ -234,6 +243,7 @@ public void doNotCrashOnNonRelatedActivityResult() {
234243
String textToBeProcessed = "Flutter!";
235244
MethodChannel.Result result = mock(MethodChannel.Result.class);
236245
processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result);
246+
ShadowLooper.runUiThreadTasks();
237247

238248
// Activity.startActivityForResult should have been called.
239249
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);

0 commit comments

Comments
 (0)