Android實現簡單畫中畫功能

Android 8.0推出瞭PictureInPicture(畫中畫功能),目前隻有在8.0以上的系統上支持。對比IOS,IOS的Picture in Picture 模式是蘋果公司在 iOS 9 中加入的一項多任務功能。下面先看一下效果:

相信不少人在平時使用ios手機的app時,已經體驗過瞭,很高興谷歌也推出瞭這項功能。

使用畫中畫模式註意點:

1.要使用畫中畫模式的Activity需要在清單文件中添加屬性:

android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
android:supportsPictureInPicture="true"

2.需要使用PictureInPictureParams類:

PictureInPictureParams.Builder mPictureInPictureParamsBuilder =
            new PictureInPictureParams.Builder();

3.添加待決定的意圖

ArrayList<RemoteAction> actions = new ArrayList<>();

 final PendingIntent intent =
                PendingIntent.getBroadcast(
                        MainActivity.this,
                        requestCode,
                        new Intent(ACTION_MEDIA_CONTROL).putExtra(EXTRA_CONTROL_TYPE, controlType),
                        0);
actions.add(new RemoteAction(icon, title, title, intent));

mPictureInPictureParamsBuilder.setActions(actions);

4.使用廣播接收各種意圖

private BroadcastReceiver mReceiver;

 mReceiver =
                    new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            if (intent == null
                                    || !ACTION_MEDIA_CONTROL.equals(intent.getAction())) {
                                return;
                            }

                            // This is where we are called back from Picture-in-Picture action items.
                            //這就是我們從畫中畫模式的操作回調的地方
                            final int controlType = intent.getIntExtra(EXTRA_CONTROL_TYPE, 0);
                            switch (controlType) {
                                case CONTROL_TYPE_PLAY:
                                    mMovieView.play();
                                    break;
                                case CONTROL_TYPE_PAUSE:
                                    mMovieView.pause();
                                    break;
                            }
                        }
                    };
            registerReceiver(mReceiver, new IntentFilter(ACTION_MEDIA_CONTROL));

5.配合自定義的MediaPlayer使用:

private MovieView mMovieView;

//各種操作
mMovieView.showControls();
mMovieView.pause();
mMovieView.play();
mMovieView.hideControls();
mMovieView.setAdjustViewBounds(false);

通過廣播接收者接收各種操作意圖,對應其操作

Demo地址:點擊查看

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: