FlutterView.java 30.6 KB
Newer Older
M
Michael Goderbauer 已提交
1
// Copyright 2013 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
package io.flutter.view;
6

7
import android.annotation.TargetApi;
8
import android.app.Activity;
9
import android.content.Context;
10
import android.content.res.Configuration;
11
import android.graphics.Bitmap;
12
import android.graphics.PixelFormat;
H
Hixie 已提交
13
import android.graphics.Rect;
14
import android.graphics.SurfaceTexture;
A
Adam Barth 已提交
15
import android.os.Build;
16
import android.os.Handler;
17
import android.os.LocaleList;
18
import android.provider.Settings;
19
import android.support.annotation.RequiresApi;
20
import android.text.format.DateFormat;
21
import android.util.AttributeSet;
22
import android.util.Log;
A
amirh 已提交
23
import android.view.*;
H
Hixie 已提交
24 25
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeProvider;
26 27
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
28
import android.view.inputmethod.InputMethodManager;
29
import io.flutter.app.FlutterPluginRegistry;
30
import io.flutter.embedding.engine.FlutterJNI;
31
import io.flutter.embedding.engine.android.AndroidKeyProcessor;
32
import io.flutter.embedding.engine.android.AndroidTouchProcessor;
33
import io.flutter.embedding.engine.dart.DartExecutor;
34
import io.flutter.embedding.engine.renderer.FlutterRenderer;
35
import io.flutter.embedding.engine.systemchannels.AccessibilityChannel;
36 37
import io.flutter.embedding.engine.systemchannels.KeyEventChannel;
import io.flutter.embedding.engine.systemchannels.LifecycleChannel;
38
import io.flutter.embedding.engine.systemchannels.LocalizationChannel;
39
import io.flutter.embedding.engine.systemchannels.NavigationChannel;
40
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
41
import io.flutter.embedding.engine.systemchannels.SettingsChannel;
42
import io.flutter.embedding.engine.systemchannels.SystemChannel;
43
import io.flutter.plugin.common.*;
44 45
import io.flutter.plugin.editing.TextInputPlugin;
import io.flutter.plugin.platform.PlatformPlugin;
46

47 48
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
A
amirh 已提交
49
import java.util.*;
50
import java.util.concurrent.atomic.AtomicLong;
51

52
/**
53
 * An Android view containing a Flutter app.
54
 */
55
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
56 57 58
    /**
     * Interface for those objects that maintain and expose a reference to a
     * {@code FlutterView} (such as a full-screen Flutter activity).
59
     *
60 61 62 63 64 65 66
     * <p>
     * This indirection is provided to support applications that use an activity
     * other than {@link io.flutter.app.FlutterActivity} (e.g. Android v4 support
     * library's {@code FragmentActivity}). It allows Flutter plugins to deal in
     * this interface and not require that the activity be a subclass of
     * {@code FlutterActivity}.
     * </p>
67 68 69
     */
    public interface Provider {
        /**
70 71
         * Returns a reference to the Flutter view maintained by this object. This may
         * be {@code null}.
72 73 74 75
         */
        FlutterView getFlutterView();
    }

76
    private static final String TAG = "FlutterView";
77

78
    static final class ViewportMetrics {
79 80 81 82 83 84 85
        float devicePixelRatio = 1.0f;
        int physicalWidth = 0;
        int physicalHeight = 0;
        int physicalPaddingTop = 0;
        int physicalPaddingRight = 0;
        int physicalPaddingBottom = 0;
        int physicalPaddingLeft = 0;
86 87 88 89
        int physicalViewInsetTop = 0;
        int physicalViewInsetRight = 0;
        int physicalViewInsetBottom = 0;
        int physicalViewInsetLeft = 0;
90 91
    }

92
    private final DartExecutor dartExecutor;
93
    private final FlutterRenderer flutterRenderer;
94 95 96
    private final NavigationChannel navigationChannel;
    private final KeyEventChannel keyEventChannel;
    private final LifecycleChannel lifecycleChannel;
97 98
    private final LocalizationChannel localizationChannel;
    private final PlatformChannel platformChannel;
99 100
    private final SettingsChannel settingsChannel;
    private final SystemChannel systemChannel;
101
    private final InputMethodManager mImm;
102
    private final TextInputPlugin mTextInputPlugin;
103
    private final AndroidKeyProcessor androidKeyProcessor;
104
    private final AndroidTouchProcessor androidTouchProcessor;
105
    private AccessibilityBridge mAccessibilityNodeProvider;
106
    private final SurfaceHolder.Callback mSurfaceCallback;
107
    private final ViewportMetrics mMetrics;
108
    private final List<ActivityLifecycleListener> mActivityLifecycleListeners;
109
    private final List<FirstFrameListener> mFirstFrameListeners;
110
    private final AtomicLong nextTextureId = new AtomicLong(0L);
111
    private FlutterNativeView mNativeView;
112 113
    private boolean mIsSoftwareRenderingEnabled = false; // using the software renderer or not

114 115 116 117 118 119 120
    private final AccessibilityBridge.OnAccessibilityChangeListener onAccessibilityChangeListener = new AccessibilityBridge.OnAccessibilityChangeListener() {
        @Override
        public void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
            resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled);
        }
    };

121
    public FlutterView(Context context) {
122 123 124
        this(context, null);
    }

125
    public FlutterView(Context context, AttributeSet attrs) {
Z
Zachary Anderson 已提交
126 127 128 129
        this(context, attrs, null);
    }

    public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
130
        super(context, attrs);
131

132
        Activity activity = (Activity) getContext();
Z
Zachary Anderson 已提交
133
        if (nativeView == null) {
134
            mNativeView = new FlutterNativeView(activity.getApplicationContext());
Z
Zachary Anderson 已提交
135 136 137
        } else {
            mNativeView = nativeView;
        }
138 139

        dartExecutor = mNativeView.getDartExecutor();
140
        flutterRenderer = new FlutterRenderer(mNativeView.getFlutterJNI());
141
        mIsSoftwareRenderingEnabled = FlutterJNI.nativeGetIsSoftwareRenderingEnabled();
142 143 144 145 146
        mMetrics = new ViewportMetrics();
        mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
        setFocusable(true);
        setFocusableInTouchMode(true);

147
        mNativeView.attachViewAndActivity(this, activity);
148 149 150

        mSurfaceCallback = new SurfaceHolder.Callback() {
            @Override
151
            public void surfaceCreated(SurfaceHolder holder) {
152
                assertAttached();
153
                mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface());
154 155 156
            }

            @Override
157
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
158
                assertAttached();
159
                mNativeView.getFlutterJNI().onSurfaceChanged(width, height);
160 161 162 163
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
164
                assertAttached();
165
                mNativeView.getFlutterJNI().onSurfaceDestroyed();
166 167 168
            }
        };
        getHolder().addCallback(mSurfaceCallback);
169

170
        mActivityLifecycleListeners = new ArrayList<>();
171
        mFirstFrameListeners = new ArrayList<>();
172

173
        // Create all platform channels
174 175 176
        navigationChannel = new NavigationChannel(dartExecutor);
        keyEventChannel = new KeyEventChannel(dartExecutor);
        lifecycleChannel = new LifecycleChannel(dartExecutor);
177 178
        localizationChannel = new LocalizationChannel(dartExecutor);
        platformChannel = new PlatformChannel(dartExecutor);
179
        systemChannel = new SystemChannel(dartExecutor);
180
        settingsChannel = new SettingsChannel(dartExecutor);
181

182 183
        // Create and setup plugins
        PlatformPlugin platformPlugin = new PlatformPlugin(activity, platformChannel);
184
        addActivityLifecycleListener(platformPlugin);
185
        mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
186
        mTextInputPlugin = new TextInputPlugin(this, dartExecutor);
187
        androidKeyProcessor = new AndroidKeyProcessor(keyEventChannel, mTextInputPlugin);
188
        androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer);
189

190 191
        // Send initial platform information to Dart
        sendLocalesToDart(getResources().getConfiguration());
192
        sendUserPlatformSettingsToDart();
193 194 195 196
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
197
        if (!isAttached()) {
198
            return super.onKeyUp(keyCode, event);
199
        }
200
        androidKeyProcessor.onKeyUp(event);
201
        return super.onKeyUp(keyCode, event);
202 203 204 205
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
206
        if (!isAttached()) {
207
            return super.onKeyDown(keyCode, event);
208
        }
209
        androidKeyProcessor.onKeyDown(event);
210
        return super.onKeyDown(keyCode, event);
211 212
    }

Z
Zachary Anderson 已提交
213 214 215 216
    public FlutterNativeView getFlutterNativeView() {
        return mNativeView;
    }

217 218 219 220
    public FlutterPluginRegistry getPluginRegistry() {
        return mNativeView.getPluginRegistry();
    }

221 222 223 224 225 226 227 228
    public String getLookupKeyForAsset(String asset) {
        return FlutterMain.getLookupKeyForAsset(asset);
    }

    public String getLookupKeyForAsset(String asset, String packageName) {
        return FlutterMain.getLookupKeyForAsset(asset, packageName);
    }

229 230 231 232
    public void addActivityLifecycleListener(ActivityLifecycleListener listener) {
        mActivityLifecycleListeners.add(listener);
    }

233
    public void onStart() {
234
        lifecycleChannel.appIsInactive();
235 236
    }

237
    public void onPause() {
238
        lifecycleChannel.appIsInactive();
239 240
    }

241
    public void onPostResume() {
242
        for (ActivityLifecycleListener listener : mActivityLifecycleListeners) {
243
            listener.onPostResume();
244
        }
245
        lifecycleChannel.appIsResumed();
246 247
    }

248
    public void onStop() {
249
        lifecycleChannel.appIsPaused();
250 251
    }

252
    public void onMemoryPressure() {
253
        systemChannel.sendMemoryPressureWarning();
254 255
    }

256
    /**
257 258
     * Provide a listener that will be called once when the FlutterView renders its
     * first frame to the underlaying SurfaceView.
259 260 261 262 263 264 265 266 267 268 269 270
     */
    public void addFirstFrameListener(FirstFrameListener listener) {
        mFirstFrameListeners.add(listener);
    }

    /**
     * Remove an existing first frame listener.
     */
    public void removeFirstFrameListener(FirstFrameListener listener) {
        mFirstFrameListeners.remove(listener);
    }

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /**
     * Updates this to support rendering as a transparent {@link SurfaceView}.
     *
     * Sets it on top of its window. The background color still needs to be
     * controlled from within the Flutter UI itself.
     */
    public void enableTransparentBackground() {
        setZOrderOnTop(true);
        getHolder().setFormat(PixelFormat.TRANSPARENT);
    }

    /**
     * Reverts this back to the {@link SurfaceView} defaults, at the back of its
     * window and opaque.
     */
    public void disableTransparentBackground() {
        setZOrderOnTop(false);
        getHolder().setFormat(PixelFormat.OPAQUE);
    }

291
    public void setInitialRoute(String route) {
292
        navigationChannel.setInitialRoute(route);
293 294
    }

295
    public void pushRoute(String route) {
296
        navigationChannel.pushRoute(route);
297 298 299
    }

    public void popRoute() {
300
        navigationChannel.popRoute();
301 302
    }

303 304 305 306 307 308 309 310 311 312 313 314 315
    private void sendUserPlatformSettingsToDart() {
        // Lookup the current brightness of the Android OS.
        boolean isNightModeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
        SettingsChannel.PlatformBrightness brightness = isNightModeOn
            ? SettingsChannel.PlatformBrightness.dark
            : SettingsChannel.PlatformBrightness.light;

        settingsChannel
            .startMessage()
            .setTextScaleFactor(getResources().getConfiguration().fontScale)
            .setUse24HourFormat(DateFormat.is24HourFormat(getContext()))
            .setPlatformBrightness(brightness)
            .send();
316
    }
317

318
    @SuppressWarnings("deprecation")
319 320
    private void sendLocalesToDart(Configuration config) {
        List<Locale> locales = new ArrayList<>();
321 322 323 324 325 326 327 328 329
        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            LocaleList localeList = config.getLocales();
            int localeCount = localeList.size();
            for (int index = 0; index < localeCount; ++index) {
                Locale locale = localeList.get(index);
                locales.add(locale);
            }
        } else {
            locales.add(config.locale);
330
        }
331
        localizationChannel.sendLocales(locales);
332 333 334 335 336
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
337
        sendLocalesToDart(newConfig);
338
        sendUserPlatformSettingsToDart();
339 340
    }

H
Hixie 已提交
341 342 343 344
    float getDevicePixelRatio() {
        return mMetrics.devicePixelRatio;
    }

Z
Zachary Anderson 已提交
345
    public FlutterNativeView detach() {
346 347
        if (!isAttached())
            return null;
Z
Zachary Anderson 已提交
348 349 350 351 352 353 354 355
        getHolder().removeCallback(mSurfaceCallback);
        mNativeView.detach();

        FlutterNativeView view = mNativeView;
        mNativeView = null;
        return view;
    }

356
    public void destroy() {
357 358
        if (!isAttached())
            return;
359

360
        getHolder().removeCallback(mSurfaceCallback);
361 362 363

        mNativeView.destroy();
        mNativeView = null;
364 365
    }

366 367
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
368
        return mTextInputPlugin.createInputConnection(this, outAttrs);
369 370
    }

371 372
    @Override
    public boolean onTouchEvent(MotionEvent event) {
373
        if (!isAttached()) {
374
            return super.onTouchEvent(event);
375
        }
376

A
Adam Barth 已提交
377 378 379 380 381 382 383 384
        // TODO(abarth): This version check might not be effective in some
        // versions of Android that statically compile code and will be upset
        // at the lack of |requestUnbufferedDispatch|. Instead, we should factor
        // version-dependent code into separate classes for each supported
        // version and dispatch dynamically.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            requestUnbufferedDispatch(event);
        }
385

386
        return androidTouchProcessor.onTouchEvent(event);
387 388
    }

389 390
    @Override
    public boolean onHoverEvent(MotionEvent event) {
391
        if (!isAttached()) {
392
            return super.onHoverEvent(event);
393
        }
394

395
        boolean handled = mAccessibilityNodeProvider.onAccessibilityHoverEvent(event);
396 397 398 399 400 401 402
        if (!handled) {
            // TODO(ianh): Expose hover events to the platform,
            // implementing ADD, REMOVE, etc.
        }
        return handled;
    }

403 404 405 406 407 408 409
    /**
     * Invoked by Android when a generic motion event occurs, e.g., joystick movement, mouse hover,
     * track pad touches, scroll wheel movements, etc.
     *
     * Flutter handles all of its own gesture detection and processing, therefore this
     * method forwards all {@link MotionEvent} data from Android to Flutter.
     */
410 411
    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
412 413
        boolean handled = isAttached() && androidTouchProcessor.onGenericMotionEvent(event);
        return handled ? true : super.onGenericMotionEvent(event);
414 415
    }

416 417 418 419
    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        mMetrics.physicalWidth = width;
        mMetrics.physicalHeight = height;
420
        updateViewportMetrics();
421 422 423
        super.onSizeChanged(width, height, oldWidth, oldHeight);
    }

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    // TODO(garyq): Add support for notch cutout API
    // Decide if we want to zero the padding of the sides. When in Landscape orientation,
    // android may decide to place the software navigation bars on the side. When the nav
    // bar is hidden, the reported insets should be removed to prevent extra useless space
    // on the sides.
    enum ZeroSides { NONE, LEFT, RIGHT, BOTH }
    ZeroSides calculateShouldZeroSides() {
        // We get both orientation and rotation because rotation is all 4
        // rotations relative to default rotation while orientation is portrait
        // or landscape. By combining both, we can obtain a more precise measure
        // of the rotation.
        Activity activity = (Activity)getContext();
        int orientation = activity.getResources().getConfiguration().orientation;
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();

        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (rotation == Surface.ROTATION_90) {
                return ZeroSides.RIGHT;
            }
            else if (rotation == Surface.ROTATION_270) {
                // In android API >= 23, the nav bar always appears on the "bottom" (USB) side.
                return Build.VERSION.SDK_INT >= 23 ? ZeroSides.LEFT : ZeroSides.RIGHT;
            }
            // Ambiguous orientation due to landscape left/right default. Zero both sides.
            else if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
                return ZeroSides.BOTH;
            }
        }
        // Square orientation deprecated in API 16, we will not check for it and return false
        // to be safe and not remove any unique padding for the devices that do use it.
        return ZeroSides.NONE;
    }

457 458 459 460 461 462 463 464
    // TODO(garyq): Use clean ways to detect keyboard instead of heuristics if possible
    // TODO(garyq): The keyboard detection may interact strangely with
    //   https://github.com/flutter/flutter/issues/22061

    // Uses inset heights and screen heights as a heuristic to determine if the insets should
    // be padded. When the on-screen keyboard is detected, we want to include the full inset
    // but when the inset is just the hidden nav bar, we want to provide a zero inset so the space
    // can be used.
465 466
    @TargetApi(20)
    @RequiresApi(20)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    int calculateBottomKeyboardInset(WindowInsets insets) {
        int screenHeight = getRootView().getHeight();
        // Magic number due to this being a heuristic. This should be replaced, but we have not
        // found a clean way to do it yet (Sept. 2018)
        final double keyboardHeightRatioHeuristic = 0.18;
        if (insets.getSystemWindowInsetBottom() < screenHeight * keyboardHeightRatioHeuristic) {
            // Is not a keyboard, so return zero as inset.
            return 0;
        }
        else {
            // Is a keyboard, so return the full inset.
            return insets.getSystemWindowInsetBottom();
        }
    }

482 483
    // This callback is not present in API < 20, which means lower API devices will see
    // the wider than expected padding when the status and navigation bars are hidden.
484
    @Override
485 486
    @TargetApi(20)
    @RequiresApi(20)
487
    public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        boolean statusBarHidden =
            (SYSTEM_UI_FLAG_FULLSCREEN & getWindowSystemUiVisibility()) != 0;
        boolean navigationBarHidden =
            (SYSTEM_UI_FLAG_HIDE_NAVIGATION & getWindowSystemUiVisibility()) != 0;

        // We zero the left and/or right sides to prevent the padding the
        // navigation bar would have caused.
        ZeroSides zeroSides = ZeroSides.NONE;
        if (navigationBarHidden) {
            zeroSides = calculateShouldZeroSides();
        }

        // The padding on top should be removed when the statusbar is hidden.
        mMetrics.physicalPaddingTop = statusBarHidden ? 0 : insets.getSystemWindowInsetTop();
        mMetrics.physicalPaddingRight =
            zeroSides == ZeroSides.RIGHT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetRight();
504
        mMetrics.physicalPaddingBottom = 0;
505 506
        mMetrics.physicalPaddingLeft =
            zeroSides == ZeroSides.LEFT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetLeft();
507 508 509 510

        // Bottom system inset (keyboard) should adjust scrollable bottom edge (inset).
        mMetrics.physicalViewInsetTop = 0;
        mMetrics.physicalViewInsetRight = 0;
511 512 513 514
        // We perform hidden navbar and keyboard handling if the navbar is set to hidden. Otherwise,
        // the navbar padding should always be provided.
        mMetrics.physicalViewInsetBottom =
            navigationBarHidden ? calculateBottomKeyboardInset(insets) : insets.getSystemWindowInsetBottom();
515
        mMetrics.physicalViewInsetLeft = 0;
516
        updateViewportMetrics();
517 518 519
        return super.onApplyWindowInsets(insets);
    }

520 521 522 523
    @Override
    @SuppressWarnings("deprecation")
    protected boolean fitSystemWindows(Rect insets) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
524
            // Status bar, left/right system insets partially obscure content (padding).
525 526
            mMetrics.physicalPaddingTop = insets.top;
            mMetrics.physicalPaddingRight = insets.right;
527
            mMetrics.physicalPaddingBottom = 0;
528
            mMetrics.physicalPaddingLeft = insets.left;
529 530 531 532

            // Bottom system inset (keyboard) should adjust scrollable bottom edge (inset).
            mMetrics.physicalViewInsetTop = 0;
            mMetrics.physicalViewInsetRight = 0;
533
            mMetrics.physicalViewInsetBottom = insets.bottom;
534
            mMetrics.physicalViewInsetLeft = 0;
535 536 537 538 539 540 541
            updateViewportMetrics();
            return true;
        } else {
            return super.fitSystemWindows(insets);
        }
    }

542
    private boolean isAttached() {
543
        return mNativeView != null && mNativeView.isAttached();
544 545
    }

546
    void assertAttached() {
547 548
        if (!isAttached())
            throw new AssertionError("Platform view is not attached");
549 550
    }

551
    private void preRun() {
H
Hixie 已提交
552
        resetAccessibilityTree();
553 554
    }

555 556 557 558 559 560
    void resetAccessibilityTree() {
        if (mAccessibilityNodeProvider != null) {
            mAccessibilityNodeProvider.reset();
        }
    }

561 562
    private void postRun() {
    }
563

564 565 566 567 568 569 570 571 572
    public void runFromBundle(FlutterRunArguments args) {
      assertAttached();
      preRun();
      mNativeView.runFromBundle(args);
      postRun();
    }

    /**
     * @deprecated
573
     * Please use runFromBundle with `FlutterRunArguments`.
574
     */
575
    @Deprecated
576 577
    public void runFromBundle(String bundlePath, String defaultPath) {
        runFromBundle(bundlePath, defaultPath, "main", false);
578 579
    }

580 581
    /**
     * @deprecated
582
     * Please use runFromBundle with `FlutterRunArguments`.
583
     */
584
    @Deprecated
585 586
    public void runFromBundle(String bundlePath, String defaultPath, String entrypoint) {
        runFromBundle(bundlePath, defaultPath, entrypoint, false);
587 588
    }

589 590
    /**
     * @deprecated
591 592
     * Please use runFromBundle with `FlutterRunArguments`.
     * Parameter `reuseRuntimeController` has no effect.
593
     */
594
    @Deprecated
595
    public void runFromBundle(String bundlePath, String defaultPath, String entrypoint, boolean reuseRuntimeController) {
596 597 598
        FlutterRunArguments args = new FlutterRunArguments();
        args.bundlePath = bundlePath;
        args.entrypoint = entrypoint;
599
        args.defaultPath = defaultPath;
600
        runFromBundle(args);
601 602
    }

603 604
    /**
     * Return the most recent frame as a bitmap.
605
     *
606 607
     * @return A bitmap.
     */
608
    public Bitmap getBitmap() {
609
        assertAttached();
610
        return mNativeView.getFlutterJNI().getBitmap();
611 612
    }

613
    private void updateViewportMetrics() {
614 615
        if (!isAttached())
            return;
616
        mNativeView.getFlutterJNI().setViewportMetrics(mMetrics.devicePixelRatio, mMetrics.physicalWidth,
617 618 619
                mMetrics.physicalHeight, mMetrics.physicalPaddingTop, mMetrics.physicalPaddingRight,
                mMetrics.physicalPaddingBottom, mMetrics.physicalPaddingLeft, mMetrics.physicalViewInsetTop,
                mMetrics.physicalViewInsetRight, mMetrics.physicalViewInsetBottom, mMetrics.physicalViewInsetLeft);
620 621

        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
622
        float fps = wm.getDefaultDisplay().getRefreshRate();
623
        VsyncWaiter.refreshPeriodNanos = (long) (1000000000.0 / fps);
624
        VsyncWaiter.refreshRateFPS = fps;
625 626
    }

627
    // Called by native to update the semantics/accessibility tree.
628
    public void updateSemantics(ByteBuffer buffer, String[] strings) {
629 630 631 632 633 634 635
        try {
            if (mAccessibilityNodeProvider != null) {
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                mAccessibilityNodeProvider.updateSemantics(buffer, strings);
            }
        } catch (Exception ex) {
            Log.e(TAG, "Uncaught exception while updating semantics", ex);
A
Adam Barth 已提交
636
        }
637 638
    }

639 640 641 642 643 644 645 646 647 648 649
    public void updateCustomAccessibilityActions(ByteBuffer buffer, String[] strings) {
        try {
            if (mAccessibilityNodeProvider != null) {
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                mAccessibilityNodeProvider.updateCustomAccessibilityActions(buffer, strings);
            }
        } catch (Exception ex) {
            Log.e(TAG, "Uncaught exception while updating local context actions", ex);
        }
    }

650
    // Called by native to notify first Flutter frame rendered.
651
    public void onFirstFrame() {
652 653 654
        // Allow listeners to remove themselves when they are called.
        List<FirstFrameListener> listeners = new ArrayList<>(mFirstFrameListeners);
        for (FirstFrameListener listener : listeners) {
655 656 657 658
            listener.onFirstFrame();
        }
    }

H
Hixie 已提交
659 660 661
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
662

663 664
        mAccessibilityNodeProvider = new AccessibilityBridge(
            this,
665
            new AccessibilityChannel(dartExecutor, getFlutterNativeView().getFlutterJNI()),
666 667 668 669
            (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE),
            getContext().getContentResolver()
        );
        mAccessibilityNodeProvider.setOnAccessibilityChangeListener(onAccessibilityChangeListener);
H
Hixie 已提交
670

671 672 673 674
        resetWillNotDraw(
            mAccessibilityNodeProvider.isAccessibilityEnabled(),
            mAccessibilityNodeProvider.isTouchExplorationEnabled()
        );
675 676
    }

H
Hixie 已提交
677 678 679
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
680 681 682

        mAccessibilityNodeProvider.release();
        mAccessibilityNodeProvider = null;
H
Hixie 已提交
683 684
    }

685 686
    // TODO(mattcarroll): Confer with Ian as to why we need this method. Delete if possible, otherwise add comments.
    private void resetWillNotDraw(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
687
        if (!mIsSoftwareRenderingEnabled) {
688
            setWillNotDraw(!(isAccessibilityEnabled || isTouchExplorationEnabled));
689 690 691
        } else {
            setWillNotDraw(false);
        }
H
Hixie 已提交
692 693
    }

H
Hixie 已提交
694 695
    @Override
    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
696
        if (mAccessibilityNodeProvider != null && mAccessibilityNodeProvider.isAccessibilityEnabled()) {
697
            return mAccessibilityNodeProvider;
698
        } else {
699 700 701 702
            // TODO(goderbauer): when a11y is off this should return a one-off snapshot of
            // the a11y
            // tree.
            return null;
703 704
        }
    }
H
Hixie 已提交
705

706 707
    @Override
    public void send(String channel, ByteBuffer message) {
708
        send(channel, message, null);
709 710 711 712
    }

    @Override
    public void send(String channel, ByteBuffer message, BinaryReply callback) {
713 714 715 716
        if (!isAttached()) {
            Log.d(TAG, "FlutterView.send called on a detached view, channel=" + channel);
            return;
        }
717
        mNativeView.send(channel, message, callback);
718 719
    }

720 721
    @Override
    public void setMessageHandler(String channel, BinaryMessageHandler handler) {
722
        mNativeView.setMessageHandler(channel, handler);
723 724
    }

725
    /**
726 727
     * Listener will be called on the Android UI thread once when Flutter renders
     * the first frame.
728
     */
729 730 731
    public interface FirstFrameListener {
        void onFirstFrame();
    }
732 733 734 735 736

    @Override
    public TextureRegistry.SurfaceTextureEntry createSurfaceTexture() {
        final SurfaceTexture surfaceTexture = new SurfaceTexture(0);
        surfaceTexture.detachFromGLContext();
737 738
        final SurfaceTextureRegistryEntry entry = new SurfaceTextureRegistryEntry(nextTextureId.getAndIncrement(),
                surfaceTexture);
739
        mNativeView.getFlutterJNI().registerTexture(entry.id(), surfaceTexture);
740 741 742 743 744 745 746 747 748 749 750
        return entry;
    }

    final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry {
        private final long id;
        private final SurfaceTexture surfaceTexture;
        private boolean released;

        SurfaceTextureRegistryEntry(long id, SurfaceTexture surfaceTexture) {
            this.id = id;
            this.surfaceTexture = surfaceTexture;
751 752 753 754 755 756 757 758 759 760 761 762

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // The callback relies on being executed on the UI thread (unsynchronised read of mNativeView
                // and also the engine code check for platform thread in Shell::OnPlatformViewMarkTextureFrameAvailable),
                // so we explicitly pass a Handler for the current thread.
                this.surfaceTexture.setOnFrameAvailableListener(onFrameListener, new Handler());
            } else {
                // Android documentation states that the listener can be called on an arbitrary thread.
                // But in practice, versions of Android that predate the newer API will call the listener
                // on the thread where the SurfaceTexture was constructed.
                this.surfaceTexture.setOnFrameAvailableListener(onFrameListener);
            }
763 764
        }

765 766 767
        private SurfaceTexture.OnFrameAvailableListener onFrameListener = new SurfaceTexture.OnFrameAvailableListener() {
            @Override
            public void onFrameAvailable(SurfaceTexture texture) {
768
                if (released || mNativeView == null) {
769 770 771 772 773
                    // Even though we make sure to unregister the callback before releasing, as of Android O
                    // SurfaceTexture has a data race when accessing the callback, so the callback may
                    // still be called by a stale reference after released==true and mNativeView==null.
                    return;
                }
774
                mNativeView.getFlutterJNI().markTextureFrameAvailable(SurfaceTextureRegistryEntry.this.id);
775 776 777
            }
        };

778 779
        @Override
        public SurfaceTexture surfaceTexture() {
780
            return surfaceTexture;
781 782 783 784 785 786 787 788 789 790 791 792 793
        }

        @Override
        public long id() {
            return id;
        }

        @Override
        public void release() {
            if (released) {
                return;
            }
            released = true;
794 795 796 797 798

            // The ordering of the next 3 calls is important:
            // First we remove the frame listener, then we release the SurfaceTexture, and only after we unregister
            // the texture which actually deletes the GL texture.

799 800 801
            // Otherwise onFrameAvailableListener might be called after mNativeView==null
            // (https://github.com/flutter/flutter/issues/20951). See also the check in onFrameAvailable.
            surfaceTexture.setOnFrameAvailableListener(null);
802
            surfaceTexture.release();
803
            mNativeView.getFlutterJNI().unregisterTexture(id);
804 805
        }
    }
806
}