diff --git a/ClockFACardDemo/README.md b/ClockFACardDemo/README.md index 214957e460384b7bc6867a526d31e0549b444aee..333df7aa67004d47e2fea4dd2d2e80df8ae0a076 100644 --- a/ClockFACardDemo/README.md +++ b/ClockFACardDemo/README.md @@ -11,13 +11,14 @@ 用户指南 • 下载此项目 -• 打开HUAWEI DevEco Studio,单击File> Open选择此ComponentCodelab +• 打开HUAWEI DevEco Studio,单击File> Open选择此ClockFACardDemo • 单击Build> Build App(s)/Hap(s)>Build Debug Hap(s)以编译hap软件包 • 单击Run> Run 'entry'以运行hap包 注意 • 您可以选择在模拟器或真机上运行hap软件包。 • 如果在真机上运行它,则需要在项目的File> Project Structure> Modules> Signing Configs中配置签名和证书信息。 +• 由于目前暂无办法保证卡片服务不被系统销毁,需要通过手机管家> 应用启动管理> 时钟服务卡片> 点击右侧滑块> 选择开启“允许后台活动”开启后台运行权限,如需要也可开启“运行自启动”。 许可 请参阅LICENSE文件以获得更多信息。 @@ -41,6 +42,7 @@ User guide Note • You can choose to run the hap package on the simulator or the phone. • If you run it on the phone, you need to configure the signature and certificate information in the project's File> Project Structure> Modules> Signing Configs. +• Currently, there is no way to ensure that the card service will not be destroyed by the system. Go to Phone Manager > App Startup Management > Pedometer Service Card, touch the slider on the right, and select Enable Background Activities to enable the background running permission. You can also enable Auto Start if necessary. Licensing Please see LICENSE for more info. diff --git a/ClockFACardDemo/build.gradle b/ClockFACardDemo/build.gradle index 1ce01d8202dede3a761267d58bd910197a647d83..859953eaf84cc3cff308056e618b42de0ed752e6 100644 --- a/ClockFACardDemo/build.gradle +++ b/ClockFACardDemo/build.gradle @@ -20,6 +20,7 @@ buildscript { } dependencies { classpath 'com.huawei.ohos:hap:2.4.4.2' + classpath 'com.huawei.ohos:decctest:1.0.0.7' } } diff --git a/ClockFACardDemo/entry/.gitignore b/ClockFACardDemo/entry/.gitignore deleted file mode 100644 index 796b96d1c402326528b4ba3c12ee9d92d0e212e9..0000000000000000000000000000000000000000 --- a/ClockFACardDemo/entry/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/ClockFACardDemo/entry/proguard-rules.pro b/ClockFACardDemo/entry/proguard-rules.pro deleted file mode 100644 index f7666e47561d514b2a76d5a7dfbb43ede86da92a..0000000000000000000000000000000000000000 --- a/ClockFACardDemo/entry/proguard-rules.pro +++ /dev/null @@ -1 +0,0 @@ -# config module specific ProGuard rules here. \ No newline at end of file diff --git a/ClockFACardDemo/entry/src/main/config.json b/ClockFACardDemo/entry/src/main/config.json index 99f43a103591bd454809fa2cc14a0a9e75813e88..d33022ed76c2b8de1c7a38231e2a76668d4b6db3 100644 --- a/ClockFACardDemo/entry/src/main/config.json +++ b/ClockFACardDemo/entry/src/main/config.json @@ -25,6 +25,18 @@ "moduleType": "entry", "installationFree": false }, + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "reason": "keep service ability backgroud running", + "usedScene": { + "ability": [ + ".StepSensorService" + ], + "when": "always" + } + } + ], "abilities": [ { "skills": [ @@ -53,10 +65,10 @@ "$layout:form_image_with_info_date_card_2_4" ], "isDefault": true, - "scheduledUpdateTime": "10:30", + "scheduledUpdateTime": "11:30", "defaultDimension": "2*2", "name": "DateCard", - "description": "This is a form card", + "description": "This is a service widget", "colorMode": "auto", "type": "Java", "supportDimensions": [ @@ -68,8 +80,16 @@ "$layout:form_image_with_info_date_card_2_4" ], "updateEnabled": true, - "updateDuration": 1, - "formVisibleNotify": true + "updateDuration": 30, + "formVisibleNotify": true, + "metaData": { + "customizeData": [ + { + "name": "needBlurBackgroundForLauncher", + "value": "true" + } + ] + } } ] }, @@ -78,7 +98,11 @@ "icon": "$media:icon", "description": "$string:TimeAbility_description", "type": "service", - "visible": false + "visible": true, + "backgroundModes": [ + "dataTransfer", + "location" + ] } ] } diff --git a/ClockFACardDemo/entry/src/main/java/com/huawei/cookbooks/TimerAbility.java b/ClockFACardDemo/entry/src/main/java/com/huawei/cookbooks/TimerAbility.java index 22a00dbc9640d24723b691c45e8539e0bbbc00d9..662c82c95a9a483926496d8d5e4c43377bc13ea1 100644 --- a/ClockFACardDemo/entry/src/main/java/com/huawei/cookbooks/TimerAbility.java +++ b/ClockFACardDemo/entry/src/main/java/com/huawei/cookbooks/TimerAbility.java @@ -20,6 +20,7 @@ import com.huawei.cookbooks.database.FormDatabase; import com.huawei.cookbooks.utils.ComponentProviderUtils; import com.huawei.cookbooks.utils.DatabaseUtils; +import com.huawei.cookbooks.utils.DateUtils; import ohos.aafwk.ability.Ability; import ohos.aafwk.ability.FormException; import ohos.aafwk.content.Intent; @@ -27,6 +28,7 @@ import ohos.agp.components.ComponentProvider; import ohos.data.DatabaseHelper; import ohos.data.orm.OrmContext; import ohos.data.orm.OrmPredicates; +import ohos.event.notification.NotificationRequest; import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; import ohos.rpc.IRemoteObject; @@ -41,6 +43,7 @@ import java.util.TimerTask; public class TimerAbility extends Ability { private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo"); private static final long SEND_PERIOD = 1000L; + private static final int NOTICE_ID = 1005; private DatabaseHelper helper = new DatabaseHelper(this); private OrmContext connect; @@ -50,8 +53,19 @@ public class TimerAbility extends Ability { connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class); startTimer(); super.onStart(intent); - } + } + private void notice() { + // 创建通知 + NotificationRequest request = new NotificationRequest(NOTICE_ID); + request.setAlertOneTime(true); + NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent(); + content.setText(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")); + NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content); + request.setContent(notificationContent); + // 绑定通知 + keepBackgroundRunning(NOTICE_ID, request); + } // 卡片更新定时器,每秒更新一次 private void startTimer() { Timer timer = new Timer(); @@ -60,6 +74,7 @@ public class TimerAbility extends Ability { @Override public void run() { updateForms(); + notice(); } }, 0, diff --git a/ClockFACardDemo/entry/src/main/resources/base/element/string.json b/ClockFACardDemo/entry/src/main/resources/base/element/string.json index de56bc1fc8ca81fb9e3e584a4646d6b3e482c7a2..cbe21bace5ea1cb0f8d6b52e7fbd93b0457b459c 100644 --- a/ClockFACardDemo/entry/src/main/resources/base/element/string.json +++ b/ClockFACardDemo/entry/src/main/resources/base/element/string.json @@ -2,7 +2,7 @@ "string": [ { "name": "app_name", - "value": "ClockCard" + "value": "时钟服务卡片" }, { "name": "mainability_description", diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java deleted file mode 100644 index bf317c0071e5a9e9d7226d82a686aa4bd13c9390..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab; - -import com.huawei.codelab.slice.MainAbilitySlice; -import com.huawei.codelab.slice.SimplePlayerAbilitySlice; -import ohos.aafwk.ability.Ability; -import ohos.aafwk.content.Intent; -import ohos.bundle.IBundleManager; - -/** - * the main page - * - * @since 2020-12-04 - * - */ -public class MainAbility extends Ability { - private static final String PERMISSION_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC"; - private static final int MY_PERMISSION_REQUEST_CODE = 1; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setMainRoute(MainAbilitySlice.class.getName()); - addActionRoute("action.video.play", SimplePlayerAbilitySlice.class.getName()); - if (verifySelfPermission(PERMISSION_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { - if (canRequestPermission(PERMISSION_DATASYNC)) { - requestPermissionsFromUser(new String[] {PERMISSION_DATASYNC}, MY_PERMISSION_REQUEST_CODE); - } - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/VideoMigrateService.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/VideoMigrateService.java deleted file mode 100644 index 743bd7c1b946e1390b9053762d835bc7a2741e7c..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/VideoMigrateService.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab; - -import com.huawei.codelab.manager.VideoMigrationStub; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.ControlCode; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.slice.SimplePlayerAbilitySlice; -import com.huawei.codelab.util.AbilitySliceRouteUtil; -import com.huawei.codelab.util.LogUtil; -import ohos.aafwk.ability.Ability; -import ohos.aafwk.content.Intent; -import ohos.aafwk.content.Operation; -import ohos.media.audio.AudioManager; -import ohos.media.audio.AudioRemoteException; -import ohos.rpc.IRemoteObject; -import ohos.rpc.RemoteException; - -/** - * VideoMigrateService - * - * @since 2020-12-04 - */ -public class VideoMigrateService extends Ability { - private static final String DESCRIPTOR = "com.huawei.codelab.ImplVideoMigration"; - private static final String TAG = VideoMigrateService.class.getName(); - private int maxVolume; - - @Override - protected void onStart(Intent intent) { - super.onStart(intent); - AudioManager mAudio = new AudioManager(getBundleName()); - try { - maxVolume = mAudio.getMaxVolume(AudioManager.AudioVolumeType.STREAM_MUSIC); - } catch (AudioRemoteException e) { - LogUtil.error(TAG, "AudioRemoteException occurs "); - } - } - - @Override - protected IRemoteObject onConnect(Intent intent) { - return new MyRemote(DESCRIPTOR); - } - - /** - * MyRemote - * - * @since 2020-12-04 - */ - private class MyRemote extends VideoMigrationStub { - /** - * constructor of MyRemote - * - * @param descriptor descriptor - */ - MyRemote(String descriptor) { - super(descriptor); - } - - @Override - public void flyIn(int startTimemiles) throws RemoteException { - Intent intent = new Intent(); - Operation operation = - new Intent.OperationBuilder() - .withBundleName(getBundleName()) - .withAbilityName(MainAbility.class.getName()) - .withAction("action.video.play") - .build(); - intent.setOperation(operation); - intent.setParam(Constants.INTENT_STARTTIME_PARAM, startTimemiles); - startAbility(intent); - } - - @Override - public void playControl(int controlCode, int extras) throws RemoteException { - ImplPlayer player = SimplePlayerAbilitySlice.getImplPlayer(); - if (player != null) { - if (controlCode == ControlCode.RESUME.getCode()) { - if (player.getPlayerStatus() == PlayerStatus.STOP - || player.getPlayerStatus() == PlayerStatus.COMPLETE) { - player.replay(); - } else { - player.resume(); - } - } else if (controlCode == ControlCode.PAUSE.getCode()) { - player.pause(); - } else if (controlCode == ControlCode.STOP.getCode()) { - player.stop(); - } else if (controlCode == ControlCode.SEEK.getCode()) { - player.rewindTo(player.getAudioDuration() * extras / Constants.ONE_HUNDRED_PERCENT); - } else if (controlCode == ControlCode.FORWARD.getCode()) { - player.rewindTo(player.getAudioCurrentPosition() + Constants.REWIND_STEP); - } else if (controlCode == ControlCode.REWARD.getCode()) { - player.rewindTo(player.getAudioCurrentPosition() - Constants.REWIND_STEP); - } else if (controlCode == ControlCode.VOLUME_SET.getCode()) { - player.setVolume(maxVolume * extras / Constants.ONE_HUNDRED_PERCENT); - } else if (controlCode == ControlCode.VOLUME_ADD.getCode()) { - player.setVolume(player.getVolume() + Constants.VOLUME_STEP); - } else if (controlCode == ControlCode.VOLUME_REDUCED.getCode()) { - player.setVolume(player.getVolume() - Constants.VOLUME_STEP); - } else { - LogUtil.info(TAG, "playControl else message"); - } - } - } - - @Override - public int flyOut() throws RemoteException { - AbilitySliceRouteUtil.getInstance().terminateAbilitySlice(); - return SimplePlayerAbilitySlice.getImplPlayer().getAudioCurrentPosition(); - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/RemoteController.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/RemoteController.java deleted file mode 100644 index a035337c2cd95747995327aa16fa744d3e25bea5..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/RemoteController.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.component; - -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.player.constant.ControlCode; -import com.huawei.codelab.util.ScreenUtils; -import ohos.agp.components.*; - -import ohos.app.Context; -import ohos.multimodalinput.event.TouchEvent; - -/** - * RemoteController - * - * @since 2020-12-04 - */ -public class RemoteController extends DependentLayout - implements Component.ClickedListener, Component.TouchEventListener, Slider.ValueChangedListener { - private static final int TOAST_DURATION = 3000; - private static final float ALPHA = 0.7f; - private Context context; - private RemoteControllerListener remoteControllerListener; - private Component componentParent; - private boolean isShown = false; - private boolean isStop = false; - private int controlCode = 0; - private int controlNumber = 0; - - /** - * constructor of RemoteController - * - * @param context context - */ - public RemoteController(Context context) { - super(context); - this.context = context; - initView(); - } - - /** - * init RemoteController view - */ - public void initView() { - setVisibility(INVISIBLE); - componentParent = - LayoutScatter.getInstance(context) - .parse(ResourceTable.Layout_remote_controller, this, false); - initButton(ResourceTable.Id_remote_resume); - initButton(ResourceTable.Id_remote_pause); - initButton(ResourceTable.Id_remote_stop); - initButton(ResourceTable.Id_remote_forward); - initButton(ResourceTable.Id_remote_reward); - initButton(ResourceTable.Id_remote_volume_up); - initButton(ResourceTable.Id_remote_volume_down); - Slider progressSlider = null; - if (componentParent.findComponentById(ResourceTable.Id_remote_progress_seek) instanceof Slider) { - progressSlider = (Slider) componentParent.findComponentById(ResourceTable.Id_remote_progress_seek); - } - progressSlider.setValueChangedListener(this); - Slider volumeSlider = null; - if (componentParent.findComponentById(ResourceTable.Id_remote_volume_seek) instanceof Slider) { - volumeSlider = (Slider) componentParent.findComponentById(ResourceTable.Id_remote_volume_seek); - } - volumeSlider.setValueChangedListener(this); - setWidth(ScreenUtils.getScreenWidth(context)); - setHeight(ScreenUtils.getScreenHeight(context)); - addComponent(componentParent); - } - - private void initButton(int res) { - Button button = null; - if (componentParent.findComponentById(res) instanceof Button) { - button = (Button) componentParent.findComponentById(res); - } - button.setClickedListener(this); - button.setTouchEventListener(this); - button.setAlpha(ALPHA); - } - - /** - * show method - */ - public void show() { - if (!isShown) { - isShown = true; - setVisibility(VISIBLE); - if (remoteControllerListener != null) { - remoteControllerListener.controllerShow(); - } - } - } - - /** - * hide method - */ - public void hide() { - if (isShown) { - isShown = false; - setVisibility(INVISIBLE); - if (remoteControllerListener != null) { - remoteControllerListener.controllerDismiss(); - } - } - } - - /** - * isShown - * - * @return boolean isShown - */ - public boolean isShown() { - return isShown; - } - - /** - * setRemoteControllerCallback - * - * @param listener listener - */ - public void setRemoteControllerCallback(RemoteControllerListener listener) { - remoteControllerListener = listener; - } - - /** - * RemoteControllerListener - * - * @since 2020-12-07 - */ - public interface RemoteControllerListener { - /** - * show the controller dialog - * - * @since 2020-12-07 - */ - void controllerShow(); - - /** - * dismiss the controller dialog - * - * @since 2020-12-07 - */ - void controllerDismiss(); - - /** - * sendControl - * - * @param code code - * @param extra extra - */ - void sendControl(int code, int extra); - } - - @Override - public boolean onTouchEvent(Component component, TouchEvent touchEvent) { - switch (touchEvent.getAction()) { - case TouchEvent.PRIMARY_POINT_DOWN: - component.setAlpha(1); - break; - case TouchEvent.PRIMARY_POINT_UP: - component.setAlpha(ALPHA); - break; - default: - break; - } - return false; - } - - @Override - public void onClick(Component component) { - if (component.getId() != ResourceTable.Id_remote_resume && isStop) { - Toast.toast(context, "Please play video first.", TOAST_DURATION); - return; - } - switch (component.getId()) { - case ResourceTable.Id_remote_resume: - isStop = false; - controlCode = ControlCode.RESUME.getCode(); - break; - case ResourceTable.Id_remote_stop: - isStop = true; - controlCode = ControlCode.STOP.getCode(); - break; - case ResourceTable.Id_remote_forward: - controlCode = ControlCode.FORWARD.getCode(); - break; - case ResourceTable.Id_remote_pause: - controlCode = ControlCode.PAUSE.getCode(); - break; - case ResourceTable.Id_remote_reward: - controlCode = ControlCode.REWARD.getCode(); - break; - case ResourceTable.Id_remote_volume_up: - controlCode = ControlCode.VOLUME_ADD.getCode(); - break; - case ResourceTable.Id_remote_volume_down: - controlCode = ControlCode.VOLUME_REDUCED.getCode(); - break; - default: - break; - } - if (remoteControllerListener != null) { - remoteControllerListener.sendControl(controlCode, 0); - } - } - - @Override - public void onProgressUpdated(Slider slider, int i, boolean isUpdate) { - } - - @Override - public void onTouchStart(Slider slider) { - } - - @Override - public void onTouchEnd(Slider slider) { - if (isStop) { - Toast.toast(context, "Please play video first.", TOAST_DURATION); - return; - } - int extras = slider.getProgress(); - switch (slider.getId()) { - case ResourceTable.Id_remote_progress_seek: - controlNumber = ControlCode.SEEK.getCode(); - break; - case ResourceTable.Id_remote_volume_seek: - controlNumber = ControlCode.VOLUME_SET.getCode(); - break; - default: - break; - } - if (remoteControllerListener != null) { - remoteControllerListener.sendControl(controlNumber, extras); - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/SlidePopupWindow.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/SlidePopupWindow.java deleted file mode 100644 index 2b9b10672e39bb8e14be05c4c430ccc5b753ce3b..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/SlidePopupWindow.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.component; - -import com.huawei.codelab.util.ScreenUtils; -import ohos.agp.animation.Animator; -import ohos.agp.animation.AnimatorProperty; -import ohos.agp.components.Component; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.LayoutScatter; -import ohos.agp.components.element.ShapeElement; -import ohos.app.Context; -import ohos.multimodalinput.event.TouchEvent; - -/** - * the window to show device list - * - * @since 2020-12-04 - */ -public class SlidePopupWindow extends DependentLayout implements Component.TouchEventListener { - /** - * SLIDE FROM BOTTOM - */ - public static final int SLIDE_FROM_BOTTOM = 1; - private static final int COLOR_FULL = 255; - private static final int ANIM_DURATION = 300; - private AnimatorProperty animatorProperty; - private int startX = 0; - private int endX = 0; - private int startY = 0; - private int endY = 0; - private boolean isShow; - private SlidePopupWindow.PopupWindowListener windowListener; - private Component rootView; - private Context windowContext; - - /** - * constructor of SlidePopupWindow - * - * @param context the context - * @param res the resources id - * @since 2020-12-07 - */ - public SlidePopupWindow(Context context, int res) { - super(context); - windowContext = context; - rootView = LayoutScatter.getInstance(windowContext).parse(res, this, false); - animatorProperty = rootView.createAnimatorProperty(); - initView(SLIDE_FROM_BOTTOM); - initListener(); - } - - private void initView(int direction) { - setVisibility(HIDE); - setWidth(ScreenUtils.getScreenWidth(windowContext)); - setHeight(ScreenUtils.getScreenHeight(windowContext)); - ShapeElement element = new ShapeElement(); - setBackground(element); - LayoutConfig config = new LayoutConfig(); - if (rootView.getLayoutConfig() instanceof LayoutConfig) { - config = (LayoutConfig) rootView.getLayoutConfig(); - } - switch (direction) { - case SLIDE_FROM_BOTTOM: - config.addRule(LayoutConfig.ALIGN_PARENT_BOTTOM); - config.setMargins(0, 0, 0, -rootView.getHeight()); - startY = ScreenUtils.getScreenHeight(windowContext); - endY = ScreenUtils.getScreenHeight(windowContext) - rootView.getHeight(); - break; - default: - break; - } - rootView.setLayoutConfig(config); - rootView.setTouchEventListener( - new TouchEventListener() { - @Override - public boolean onTouchEvent(Component component, TouchEvent touchEvent) { - return true; - } - }); - addComponent(rootView); - } - - private void initListener() { - setTouchEventListener(this); - animatorProperty.setStateChangedListener( - new Animator.StateChangedListener() { - @Override - public void onStart(Animator animator) { - if (isShow) { - if (windowListener != null) { - windowListener.windowShow(); - } - setVisibility(VISIBLE); - } - } - - @Override - public void onStop(Animator animator) { - } - - @Override - public void onCancel(Animator animator) { - } - - @Override - public void onEnd(Animator animator) { - if (!isShow) { - setVisibility(INVISIBLE); - if (windowListener != null) { - windowListener.windowDismiss(); - } - } - } - - @Override - public void onPause(Animator animator) { - } - - @Override - public void onResume(Animator animator) { - } - }); - } - - @Override - public boolean onTouchEvent(Component component, TouchEvent touchEvent) { - hide(); - return true; - } - - /** - * PopupWindowListener - * - * @since 2020-12-07 - */ - public interface PopupWindowListener { - /** - * show the device list window - * - * @since 2020-12-07 - */ - void windowShow(); - - /** - * dismiss the device list window - * - * @since 2020-12-07 - */ - void windowDismiss(); - } - - /** - * setPopupWindowListener - * - * @param listener listener - */ - public void setPopupWindowListener(SlidePopupWindow.PopupWindowListener listener) { - windowListener = listener; - } - - /** - * show of SlidePopupWindow - */ - public void show() { - if (!isShow) { - isShow = true; - animatorProperty - .moveFromX(startX) - .moveToX(endX) - .moveFromY(startY) - .moveToY(endY) - .setCurveType(Animator.CurveType.LINEAR) - .setDuration(ANIM_DURATION) - .start(); - } - } - - /** - * hide of SlidePopupWindow - */ - public void hide() { - if (isShow) { - isShow = false; - animatorProperty - .moveFromX(endX) - .moveToX(startX) - .moveFromY(endY) - .moveToY(startY) - .setCurveType(Animator.CurveType.LINEAR) - .setDuration(ANIM_DURATION) - .start(); - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/Toast.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/Toast.java deleted file mode 100644 index 0c4a43511f64dea645b6f08ef57c018a47845606..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/component/Toast.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.component; - -import com.huawei.codelab.util.ScreenUtils; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.Text; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.utils.Color; -import ohos.agp.window.dialog.ToastDialog; -import ohos.app.Context; - -/** - * Toast - * - * @since 2020-12-04 - */ -public class Toast { - private static final int TEXT_SIZE = 40; - private static final int TEXT_PADDING = 20; - private static final int TEXT_HEIGHT = 100; - private static final int TEXT_CORNER = 20; - private static final int TEXT_OFFSETY = 200; - private static final int TEXT_ALPHA = 120; - - private Toast() { - } - - /** - * toast - * - * @param context the context - * @param text the toast content - * @param ms the toast ime,ms - */ - public static void toast(Context context, String text, int ms) { - DependentLayout layout = new DependentLayout(context); - layout.setWidth(ScreenUtils.getScreenWidth(context)); - layout.setHeight(TEXT_HEIGHT); - Text textView = new Text(context); - ShapeElement background = new ShapeElement(); - background.setCornerRadius(TEXT_CORNER); - background.setRgbColor(new RgbColor(0, 0, 0, TEXT_ALPHA)); - textView.setBackground(background); - DependentLayout.LayoutConfig config = - new DependentLayout.LayoutConfig( - DependentLayout.LayoutConfig.MATCH_CONTENT, DependentLayout.LayoutConfig.MATCH_CONTENT); - config.addRule(DependentLayout.LayoutConfig.HORIZONTAL_CENTER); - textView.setLayoutConfig(config); - textView.setPadding(TEXT_PADDING, TEXT_PADDING, TEXT_PADDING, TEXT_PADDING); - textView.setMaxTextLines(1); - textView.setTextSize(TEXT_SIZE); - textView.setMaxTextWidth(ScreenUtils.getScreenWidth(context)); - textView.setTextColor(Color.WHITE); - textView.setText(text); - layout.addComponent(textView); - ToastDialog toastDialog = new ToastDialog(context); - toastDialog.setContentCustomComponent(layout); - toastDialog.setTransparent(true); - toastDialog.setOffset(0, TEXT_OFFSETY); - toastDialog.setSize(ScreenUtils.getScreenWidth(context), TEXT_HEIGHT); - toastDialog.setDuration(ms); - toastDialog.show(); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/AdvertisementMo.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/AdvertisementMo.java deleted file mode 100644 index 121af6b1ebfeed675231768022856857fb5723da..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/AdvertisementMo.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.data; - -/** - * AdvertisementMo object - * - * @since 2020-12-04 - * - */ -public class AdvertisementMo { - private int sourceId; - - private String description; - - /** - * constructor - * - * @param sourceId graphic id - * @param description advertisement description - */ - public AdvertisementMo(int sourceId, String description) { - this.sourceId = sourceId; - this.description = description; - } - - public int getSourceId() { - return sourceId; - } - - public void setSourceId(int sourceId) { - this.sourceId = sourceId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoListMo.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoListMo.java deleted file mode 100644 index 2f56138b98ee9247ef401c8711bdd0acf899950d..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoListMo.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.data; - -/** - * VideoList object - * - * @since 2020-12-04 - * - */ -public class VideoListMo { - private int sourceId; - - private String name; - - private String description; - - /** - * VideoListMo - * - * @param sourceId sourceId - * @param name name - * @param description description - */ - public VideoListMo(int sourceId, String name, String description) { - this.sourceId = sourceId; - this.name = name; - this.description = description; - } - - public int getSourceId() { - return sourceId; - } - - public void setSourceId(int sourceId) { - this.sourceId = sourceId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoTabStyle.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoTabStyle.java deleted file mode 100644 index 5d5c05ad5e937fa5cc32c76d17773e279f34a29b..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/data/VideoTabStyle.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.data; - -/** - * Video Component style - * - * @since 2020-12-04 - */ -public class VideoTabStyle { - /** - * BOLD FONT NAME - * - */ - public static final String BOLD_FONT_NAME = "微软雅黑"; - /** - * INDICATOR OFFSET - * - */ - public static final int INDICATOR_OFFSET = 12; - /** - * INDICATOR NORMA ALPHA - * - */ - public static final int INDICATOR_NORMA_ALPHA = 168; - /** - * INDICATOR BONDS - * - */ - public static final int INDICATOR_BONDS = 20; - /** - * ADVERTISEMENT SLID PROID - * - */ - public static final int ADVERTISEMENT_SLID_PROID = 3; - /** - * ADVERTISEMENT SLID DELAY - * - */ - public static final int ADVERTISEMENT_SLID_DELAY = 3; - - /** - * constructor of VideoTabStyle - * - */ - private VideoTabStyle() { - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/ImplVideoMigration.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/ImplVideoMigration.java deleted file mode 100644 index dc5a6991b10bbac45077ff84a19fc07d3b5eba9e..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/ImplVideoMigration.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.manager; - -import ohos.rpc.IRemoteBroker; -import ohos.rpc.RemoteException; - -/** - * the main page - * - * @since 2020-12-04 - * - */ - -public interface ImplVideoMigration extends IRemoteBroker { - /** - * flyIn - * - * @param startTimemiles startTimemiles - * @throws RemoteException RemoteException - */ - void flyIn( - /* [in] */ int startTimemiles) throws RemoteException; - - /** - * playControl - * - * @param controlCode controlCode - * @param extras extras - * @throws RemoteException RemoteException - */ - void playControl( - /* [in] */ int controlCode, - /* [in] */ int extras) throws RemoteException; - - /** - * flyOut - * - * @return rturn the status code - * @throws RemoteException RemoteException - */ - int flyOut() throws RemoteException; -} - diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationProxy.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationProxy.java deleted file mode 100644 index 91016d7097494b8a12d880c78579b1cd5ce34a4f..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationProxy.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.manager; - -import ohos.rpc.IRemoteObject; -import ohos.rpc.MessageOption; -import ohos.rpc.MessageParcel; -import ohos.rpc.RemoteException; - -/** - * the main page - * - * @since 2020-12-04 - * - */ -public class VideoMigrationProxy implements ImplVideoMigration { - private static final String DESCRIPTOR = "com.huawei.codelab.ImplVideoMigration"; - private static final int COMMAND_FLY_IN = IRemoteObject.MIN_TRANSACTION_ID + 0; - private static final int COMMAND_PLAY_CONTROL = IRemoteObject.MIN_TRANSACTION_ID + 1; - private static final int COMMAND_FLY_OUT = IRemoteObject.MIN_TRANSACTION_ID + 2; - private static final int ERR_OK = 0; - private static final String TAG = "VideoMigrationProxy"; - - private final IRemoteObject remote; - - /** - * constructor of VideoMigrationProxy - * - * @param remote remote - */ - public VideoMigrationProxy( - /* [in] */ IRemoteObject remote) { - this.remote = remote; - } - - @Override - public IRemoteObject asObject() { - return remote; - } - - @Override - public void flyIn( - - /* [in] */ int startTimemiles) throws RemoteException { - MessageParcel data = MessageParcel.obtain(); - MessageParcel reply = MessageParcel.obtain(); - MessageOption option = new MessageOption(MessageOption.TF_SYNC); - - data.writeInterfaceToken(DESCRIPTOR); - data.writeInt(startTimemiles); - - try { - remote.sendRequest(COMMAND_FLY_IN, data, reply, option); - reply.readException(); - } finally { - data.reclaim(); - reply.reclaim(); - } - } - - @Override - public void playControl( - /* [in] */ int controlCode, - /* [in] */ int extras) throws RemoteException { - MessageParcel data = MessageParcel.obtain(); - MessageParcel reply = MessageParcel.obtain(); - MessageOption option = new MessageOption(MessageOption.TF_SYNC); - - data.writeInterfaceToken(DESCRIPTOR); - data.writeInt(controlCode); - data.writeInt(extras); - - try { - remote.sendRequest(COMMAND_PLAY_CONTROL, data, reply, option); - reply.readException(); - } finally { - data.reclaim(); - reply.reclaim(); - } - } - - @Override - public int flyOut() throws RemoteException { - MessageParcel data = MessageParcel.obtain(); - MessageParcel reply = MessageParcel.obtain(); - MessageOption option = new MessageOption(MessageOption.TF_SYNC); - - data.writeInterfaceToken(DESCRIPTOR); - try { - remote.sendRequest(COMMAND_FLY_OUT, data, reply, option); - reply.readException(); - int result = reply.readInt(); - return result; - } finally { - data.reclaim(); - reply.reclaim(); - } - } -} - diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationStub.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationStub.java deleted file mode 100644 index 0d63e7e3d4c84370aa3700402965569218337fb6..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/manager/VideoMigrationStub.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.manager; - -import ohos.rpc.IRemoteBroker; -import ohos.rpc.IRemoteObject; -import ohos.rpc.MessageOption; -import ohos.rpc.MessageParcel; -import ohos.rpc.RemoteException; -import ohos.rpc.RemoteObject; - -/** - * the main page - * - * @since 2020-12-07 - * - */ -public abstract class VideoMigrationStub extends RemoteObject implements ImplVideoMigration { - private static final String DESCRIPTOR = "com.huawei.codelab.ImplVideoMigration"; - private static final String TAG = "VideoMigrationStub"; - private static final int COMMAND_FLY_IN = IRemoteObject.MIN_TRANSACTION_ID + 0; - private static final int COMMAND_PLAY_CONTROL = IRemoteObject.MIN_TRANSACTION_ID + 1; - private static final int COMMAND_FLY_OUT = IRemoteObject.MIN_TRANSACTION_ID + 2; - private static final int ERR_OK = 0; - private static final int ERR_RUNTIME_EXCEPTION = -1; - - /** - * constructor of VideoMigrationStub - * - * @param descriptor descriptor - */ - public VideoMigrationStub( - /* [in] */ String descriptor) { - super(descriptor); - } - - @Override - public IRemoteObject asObject() { - return this; - } - - /** - * Video Migration - * - * @param object IRemoteObject - * @return ImplVideoMigration - */ - public static ImplVideoMigration asInterface(IRemoteObject object) { - ImplVideoMigration result = null; - if (object == null) { - return result; - } - IRemoteBroker broker = object.queryLocalInterface(DESCRIPTOR); - if (broker != null) { - if (broker instanceof ImplVideoMigration) { - result = (ImplVideoMigration)broker; - } - } else { - result = new VideoMigrationProxy(object); - } - - return result; - } - - @Override - public boolean onRemoteRequest( - /* [in] */ int code, - /* [in] */ MessageParcel data, - /* [out] */ MessageParcel reply, - /* [in] */ MessageOption option) throws RemoteException { - String token = data.readInterfaceToken(); - if (!DESCRIPTOR.equals(token)) { - return false; - } - switch (code) { - case COMMAND_FLY_IN: { - int startTimemiles = data.readInt(); - flyIn(startTimemiles); - reply.writeNoException(); - return true; - } - case COMMAND_PLAY_CONTROL: { - int controlCode = data.readInt(); - int extras = data.readInt(); - playControl(controlCode, extras); - reply.writeNoException(); - return true; - } - case COMMAND_FLY_OUT: { - int result; - result = flyOut(); - reply.writeNoException(); - reply.writeInt(result); - return true; - } - default: - return super.onRemoteRequest(code, data, reply, option); - } - } -} - diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java deleted file mode 100644 index 0e67bc4aea034430b2028fe190d25492183cc42e..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player; - -import com.huawei.codelab.player.api.ImplLifecycle; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.api.ScreenChangeListener; -import com.huawei.codelab.player.api.StatusChangeListener; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.player.factory.SourceFactory; -import com.huawei.codelab.player.manager.HmPlayerLifecycle; -import com.huawei.codelab.util.DateUtils; -import com.huawei.codelab.util.LogUtil; -import ohos.agp.components.Component; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.surfaceprovider.SurfaceProvider; -import ohos.agp.graphics.Surface; -import ohos.agp.graphics.SurfaceOps; -import ohos.agp.window.service.WindowManager; -import ohos.app.Context; -import ohos.media.audio.AudioManager; -import ohos.media.audio.AudioRemoteException; -import ohos.media.common.Source; -import ohos.media.player.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Hm player - * - * @since 2020-12-04 - */ -public class HmPlayer implements ImplPlayer { - private static final String TAG = "HmPlayer"; - private static final int MICRO_MILLI_RATE = 1000; - private static final int MAX_MUSIC_VOLUME = 100; - private static final int MIM_MUSIC_VOLUME = 0; - private static final int CAPACITY = 6; - private static final int CORE_POOL_SIZE = 2; - private static final int MAX_POOL_SIZE = 20; - private static final int KEEP_ALIVE_TIME = 3; - private Player player; - private SurfaceProvider surfaceView; - private Surface surface; - private AudioManager audio; - private HmPlayerLifecycle lifecycle; - private Builder playerBuilder; - private PlayerStatus status = PlayerStatus.IDEL; - - private List statusChangeCallbacks = new ArrayList<>(0); - private List screenChangeCallbacks = new ArrayList<>(0); - private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, - KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<>(CAPACITY), - new ThreadPoolExecutor.DiscardOldestPolicy()); - private boolean isSurfaceViewCreated; - - private SurfaceOps.Callback surfaceCallback = new SurfaceOps.Callback() { - @Override - public void surfaceCreated(SurfaceOps surfaceOps) { - LogUtil.info(TAG, "surfaceCreated"); - isSurfaceViewCreated = true; - surface = surfaceOps.getSurface(); - start(); - } - - @Override - public void surfaceChanged(SurfaceOps surfaceOps, int i, int width, int height) { - LogUtil.info(TAG, "surfaceChanged i is " + i + ",width is " + width + ",height is " + height); - } - - @Override - public void surfaceDestroyed(SurfaceOps surfaceOps) { - LogUtil.info(TAG, "surfaceDestroyed"); - isSurfaceViewCreated = false; - } - }; - - /** - * constructor of HmPlayer - * - * @param builder builder - */ - private HmPlayer(Builder builder) { - playerBuilder = builder; - WindowManager.getInstance().getTopWindow().get().setTransparent(true); // 不设置窗体透明会挡住播放内容,除非设置pinToZTop为true - audio = new AudioManager(playerBuilder.mContext.getBundleName()); - lifecycle = new HmPlayerLifecycle(this); - surfaceView = new SurfaceProvider(playerBuilder.mContext); - DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig(); - layoutConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); - surfaceView.setLayoutConfig(layoutConfig); - surfaceView.setVisibility(Component.VISIBLE); - surfaceView.setFocusable(Component.FOCUS_ENABLE); - surfaceView.setTouchFocusable(true); - surfaceView.requestFocus(); - surfaceView.pinToZTop(playerBuilder.isTopPlay); - surfaceView.getSurfaceOps().get().addCallback(surfaceCallback); - } - - /** - * HmPlayer Callback - * - * @since 2020-12-04 - */ - private class HmPlayerCallback implements Player.IPlayerCallback { - @Override - public void onPrepared() { - LogUtil.info(TAG, "onPrepared is called "); - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PREPARED; - callback.statusCallback(PlayerStatus.PREPARED); - } - } - - @Override - public void onMessage(int info, int i1) { - LogUtil.info(TAG, "onMessage info is " + info + ",i1 is" + i1); - if (info == Player.PLAYER_INFO_VIDEO_RENDERING_START && i1 == 0) { - // start to rendering ,show controller - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PLAY; - callback.statusCallback(PlayerStatus.PLAY); - } - } else if (info == Player.PLAYER_INFO_BUFFERING_START && i1 == 0) { - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.BUFFERING; - callback.statusCallback(PlayerStatus.BUFFERING); - } - } else if (info == Player.PLAYER_INFO_BUFFERING_END && i1 == 0) { - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PLAY; - callback.statusCallback(PlayerStatus.PLAY); - } - } else { - LogUtil.info(TAG, "onMessage else message"); - } - } - - @Override - public void onError(int i, int i1) { - LogUtil.info(TAG, "onError is called ,i is " + i + ",i1 is " + i1); - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.ERROR; - callback.statusCallback(PlayerStatus.ERROR); - } - release(); - } - - @Override - public void onResolutionChanged(int x, int y) { - LogUtil.info(TAG, "onResolutionChanged i is " + x + ",i1 is " + y); - if (!playerBuilder.isStretch && x != 0 && y != 0) { - getBuilder().mContext.getUITaskDispatcher().delayDispatch(new Runnable() { - @Override - public void run() { - if (x > y) { - surfaceView.setWidth(surfaceView.getWidth()); - surfaceView.setHeight(Math.min(y * surfaceView.getWidth() / x, surfaceView.getHeight())); - } else { - surfaceView.setHeight(surfaceView.getHeight()); - surfaceView.setWidth(Math.min(x * surfaceView.getHeight() / y, surfaceView.getWidth())); - } - } - }, 0); - } - } - - @Override - public void onPlayBackComplete() { - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.COMPLETE; - callback.statusCallback(PlayerStatus.COMPLETE); - } - stop(); - } - - @Override - public void onRewindToComplete() { - resume(); - if (playerBuilder.isPause) { - playerBuilder.isPause = false; - pause(); - } - } - - @Override - public void onBufferingChange(int i) { - } - - @Override - public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) { - LogUtil.info(TAG, "onNewTimedMetaData is called"); - } - - @Override - public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) { - LogUtil.info(TAG, "onMediaTimeIncontinuity is called"); - } - } - - /** - * start time consuming operation - */ - private void start() { - if (isSurfaceViewCreated) { - threadPoolExecutor.execute(() -> { - player.setVideoSurface(surface); - player.prepare(); - if (playerBuilder.startMillisecond > 0) { - int microsecond = playerBuilder.startMillisecond * MICRO_MILLI_RATE; - player.rewindTo(microsecond); - } else { - player.play(); - } - }); - } - } - - @Override - public SurfaceProvider getPlayerView() { - return surfaceView; - } - - @Override - public ImplLifecycle getLifecycle() { - return lifecycle; - } - - @Override - public void addPlayerStatusCallback(StatusChangeListener callback) { - if (callback != null) { - statusChangeCallbacks.add(callback); - } - } - - @Override - public void removePlayerStatuCallback(StatusChangeListener callback) { - statusChangeCallbacks.remove(callback); - } - - @Override - public void addPlayerViewCallback(ScreenChangeListener callback) { - if (callback != null) { - screenChangeCallbacks.add(callback); - } - } - - @Override - public void removePlayerViewCallback(ScreenChangeListener callback) { - screenChangeCallbacks.remove(callback); - } - - @Override - public Builder getBuilder() { - return playerBuilder; - } - - @Override - public PlayerStatus getPlayerStatus() { - return status; - } - - @Override - public void play() { - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PREPARING; - callback.statusCallback(PlayerStatus.PREPARING); - } - release(); - player = new Player(playerBuilder.mContext); - player.setPlayerCallback(new HmPlayerCallback()); - Source source = new SourceFactory(playerBuilder.mContext, playerBuilder.filePath).getSource(); - player.setSource(source); - start(); - } - - @Override - public void replay() { - if (isPlaying()) { - rewindTo(0); - } else { - reload(playerBuilder.filePath, 0); - } - } - - @Override - public void reload(String filepath, int startMillisecond) { - playerBuilder.filePath = filepath; - playerBuilder.startMillisecond = startMillisecond; - play(); - } - - @Override - public void stop() { - if (player == null) { - return; - } - player.stop(); - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.STOP; - callback.statusCallback(PlayerStatus.STOP); - } - } - - @Override - public void release() { - if (player == null) { - return; - } - if (status != PlayerStatus.IDEL) { - player.release(); - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.IDEL; - callback.statusCallback(PlayerStatus.IDEL); - } - } - } - - /** - * resume playback - */ - @Override - public void resume() { - if (player == null) { - return; - } - if (status != PlayerStatus.IDEL) { - if (!isPlaying()) { - player.play(); - } - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PLAY; - callback.statusCallback(PlayerStatus.PLAY); - } - } - } - - /** - * pause playback - */ - @Override - public void pause() { - if (player == null) { - return; - } - if (isPlaying()) { - player.pause(); - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.PAUSE; - callback.statusCallback(PlayerStatus.PAUSE); - } - } - } - - /** - * Get audio current play position - * - * @return play position - */ - @Override - public int getAudioCurrentPosition() { - if (player == null) { - return 0; - } - return player.getCurrentTime(); - } - - /** - * Get audio duration - * - * @return audio duration - */ - @Override - public int getAudioDuration() { - if (player == null) { - return 0; - } - return player.getDuration(); - } - - @Override - public int getVolume() { - int curVolume = 0; - if (audio == null) { - return curVolume; - } - try { - curVolume = audio.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC); - } catch (AudioRemoteException e) { - LogUtil.error(TAG, "get current volume failed"); - } - return curVolume; - } - - @Override - public void setVolume(int volume) { - if (audio == null) { - return; - } - if (volume > MAX_MUSIC_VOLUME) { - audio.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MAX_MUSIC_VOLUME); - } else if (volume < MIM_MUSIC_VOLUME) { - audio.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MIM_MUSIC_VOLUME); - } else { - audio.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, volume); - } - } - - /** - * set play speed - * - * @param speed 0~12 - */ - @Override - public void setPlaySpeed(float speed) { - if (player == null) { - return; - } - if (status != PlayerStatus.IDEL) { - player.setPlaybackSpeed(speed); - } - } - - @Override - public void changeScreen() { - } - - /** - * whether player is running or not - * - * @return isPlaying boolean - */ - @Override - public boolean isPlaying() { - return player.isNowPlaying(); - } - - /** - * Rewind to specified time position - * - * @param startMicrosecond time - */ - @Override - public void rewindTo(int startMicrosecond) { - if (player == null) { - return; - } - if (status != PlayerStatus.IDEL) { - for (StatusChangeListener callback : statusChangeCallbacks) { - status = PlayerStatus.BUFFERING; - callback.statusCallback(PlayerStatus.BUFFERING); - } - player.rewindTo(startMicrosecond * MICRO_MILLI_RATE); - } - } - - @Override - public String getDurationText() { - return DateUtils.msToString(getAudioDuration()); - } - - @Override - public String getCurrentText() { - return DateUtils.msToString(getAudioCurrentPosition()); - } - - /** - * Builder - * - * @since 2020-12-04 - */ - public static class Builder { - private Context mContext; - private String filePath = ""; - private int startMillisecond = 0; - private boolean isTopPlay; - private boolean isStretch; - private boolean isPause; - - /** - * constructor of Builder - * - * @param context context - */ - public Builder(Context context) { - mContext = context; - } - - /** - * setFilePath of Builder - * - * @param filePath filePath - * @return builder - */ - public Builder setFilePath(String filePath) { - this.filePath = filePath; - return this; - } - - /** - * getFilePath of Builder - * - * @return filePath - */ - public String getFilePath() { - return filePath; - } - - /** - * setStartMillisecond of Builder - * - * @param startMillisecond startMillisecond - * @return builder - */ - public Builder setStartMillisecond(int startMillisecond) { - this.startMillisecond = startMillisecond; - return this; - } - - /** - * getStartMillisecond of Builder - * - * @return startMillisecond - */ - public int getStartMillisecond() { - return startMillisecond; - } - - /** - * setTopPlay of Builder - * - * @param topPlay topPlay - * @return Builder - */ - public Builder setTopPlay(boolean topPlay) { - isTopPlay = topPlay; - return this; - } - - /** - * setStretch of Builder - * - * @param stretch stretch - * @return Builder - */ - public Builder setStretch(boolean stretch) { - isStretch = stretch; - return this; - } - - /** - * setPause of Builder - * - * @param pause pause - * @return Builder - */ - public Builder setPause(boolean pause) { - isPause = pause; - return this; - } - - /** - * create of ImplPlayer - * - * @return ImplPlayer - */ - public ImplPlayer create() { - return new HmPlayer(this); - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java deleted file mode 100644 index bb71f199c610e012efbd2e2556c6c443ba46e345..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -/** - * ImplLifecycle - * - * @since 2020-12-04 - */ - -public interface ImplLifecycle { - /** - * start the HmPlayer - * - */ - void onStart(); - - /** - * turn the HmPlayer foreground - * - */ - void onForeground(); - - /** - * turn the HmPlayer to background - * - */ - void onBackground(); - - /** - * stop the HmPlayer - * - */ - void onStop(); -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java deleted file mode 100644 index b196877aa565aba40a4d6443c3bda705fbe66310..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -import com.huawei.codelab.player.HmPlayer; -import com.huawei.codelab.player.constant.PlayerStatus; -import ohos.agp.components.surfaceprovider.SurfaceProvider; - -/** - * IPlayer interface - * - * @since 2020-12-04 - * - */ -public interface ImplPlayer { - /** - * Player - * - * @param callback callback - */ - void addPlayerStatusCallback(StatusChangeListener callback); - - /** - * Player - * - * @param callback callback - */ - void removePlayerStatuCallback(StatusChangeListener callback); - - /** - * Player - * - * @param callback callback - */ - void addPlayerViewCallback(ScreenChangeListener callback); - - /** - * Player - * - * @param callback callback - */ - void removePlayerViewCallback(ScreenChangeListener callback); - - /** - * play the video - * - */ - void play(); - - /** - * replay - * - */ - void replay(); - - /** - * reload - * - * @param filepath filepath - * @param startMillisecond startMillisecond - */ - void reload(String filepath, int startMillisecond); - - /** - * resume - * - */ - void resume(); - - /** - * pause - * - */ - void pause(); - - /** - * getAudioCurrentPosition - * - * @return int - */ - int getAudioCurrentPosition(); - - /** - * getAudioDuration - * - * @return int - */ - int getAudioDuration(); - - /** - * getDurationText - * - * @return string - */ - String getDurationText(); - - /** - * getCurrentText - * - * @return string - */ - String getCurrentText(); - - /** - * getVolume - * - * @return int - */ - int getVolume(); - - /** - * setVolume - * - * @param volume volume - */ - void setVolume(int volume); - - /** - * setPlaySpeed - * - * @param speed speed - */ - void setPlaySpeed(float speed); - - /** - * change the screen direction - * - */ - void changeScreen(); - - /** - * rewindTo - * - * @param startMicrosecond startMicrosecond - */ - void rewindTo(int startMicrosecond); - - /** - * isPlaying - * - * @return true - */ - boolean isPlaying(); - - /** - * stop the video - * - */ - void stop(); - - /** - * release the video - * - */ - void release(); - - /** - * getPlayerView - * - * @return SurfaceProvider - */ - SurfaceProvider getPlayerView(); - - /** - * getLifecycle - * - * @return ImplLifecycle - */ - ImplLifecycle getLifecycle(); - - /** - * getBuilder - * - * @return Builder - */ - HmPlayer.Builder getBuilder(); - - /** - * getPlayerStatu - * - * @return PlayerStatus.java - */ - PlayerStatus getPlayerStatus(); -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java deleted file mode 100644 index 8832f8a1d1e9d7bb1eae266e8475cde6ac791476..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -/** - * ScreenChangeListener interface - * - * @since 2020-12-04 - * - */ -public interface ScreenChangeListener { - /** - * screenCallback - * - * @param width width - * @param height height - */ - void screenCallback(int width, int height); -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatusChangeListener.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatusChangeListener.java deleted file mode 100644 index 6d3193455912114d4e970f5551e96b6f444ca579..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatusChangeListener.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -import com.huawei.codelab.player.constant.PlayerStatus; - -/** - * StatusChangeListener interface - * - * @since 2020-12-04 - * - */ -public interface StatusChangeListener { - /** - * statusCallback - * - * @param status status - */ - void statusCallback(PlayerStatus status); -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/PlayerLoading.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/PlayerLoading.java deleted file mode 100644 index 8d74510a16d911a323722846df007f1de272dc1d..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/PlayerLoading.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.component; - -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.api.StatusChangeListener; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.util.LogUtil; -import ohos.agp.animation.AnimatorProperty; -import ohos.agp.components.*; -import ohos.app.Context; - -/** - * PlayerLoading - * - * @since 2020-12-04 - */ -public class PlayerLoading extends ComponentContainer { - private static final int HALF_NUMBER = 2; - private static final int ANIM_ROTATE = 360; - private static final int ANIM_DURATION = 2000; - private static final int ANIM_LOOPED_COUNT = -1; - private ImplPlayer player; - private Image loading; - private AnimatorProperty loadingAnim; - - /** - * constructor of PlayerLoading - * - * @param context builder - * @param player player - */ - public PlayerLoading(Context context, ImplPlayer player) { - super(context); - this.player = player; - initView(context); - initListener(); - } - - private void initView(Context context) { - DependentLayout.LayoutConfig layoutConfig = - new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT); - setLayoutConfig(layoutConfig); - Component loadingContainer = LayoutScatter.getInstance(context).parse( - ResourceTable.Layout_player_loading_layout, null, false); - if (loadingContainer.findComponentById(ResourceTable.Id_image_loading) instanceof Image) { - loading = (Image) loadingContainer.findComponentById(ResourceTable.Id_image_loading); - } - addComponent(loadingContainer); - initAnim(); - hide(); - } - - private void initAnim() { - int with = loading.getWidth() / HALF_NUMBER; - int height = loading.getHeight() / HALF_NUMBER; - loading.setPivotX(with); - loading.setPivotY(height); - loadingAnim = loading.createAnimatorProperty(); - loadingAnim.rotate(ANIM_ROTATE).setDuration(ANIM_DURATION).setLoopedCount(ANIM_LOOPED_COUNT); - } - - private void initListener() { - player.addPlayerStatusCallback(new StatusChangeListener() { - @Override - public void statusCallback(PlayerStatus status) { - mContext.getUITaskDispatcher().delayDispatch( - new Runnable() { - @Override - public void run() { - if (status == PlayerStatus.PREPARING || status == PlayerStatus.BUFFERING) { - show(); - } else if (status == PlayerStatus.PLAY) { - hide(); - } else { - LogUtil.info(PlayerLoading.class.getName(), - "statuCallback else message"); - } - } - }, - 0); - } - }); - } - - /** - * show of PlayerLoading - */ - public void show() { - if (loadingAnim.isPaused()) { - loadingAnim.resume(); - } else { - loadingAnim.start(); - } - setVisibility(VISIBLE); - } - - /** - * hide of PlayerLoading - */ - public void hide() { - setVisibility(INVISIBLE); - loadingAnim.pause(); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/SimplePlayerController.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/SimplePlayerController.java deleted file mode 100644 index 1f604890fd8e773b2b95465de9c7de036db3d7a9..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/component/SimplePlayerController.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.component; - -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.api.StatusChangeListener; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.util.DateUtils; -import com.huawei.codelab.util.LogUtil; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.*; -import ohos.agp.components.element.ShapeElement; -import ohos.app.Context; -import ohos.eventhandler.EventHandler; -import ohos.eventhandler.EventRunner; -import ohos.eventhandler.InnerEvent; - -/** - * PlayerController - * - * @since 2020-12-04 - */ -public class SimplePlayerController extends ComponentContainer { - private static final int THUMB_RED = 255; - private static final int THUMB_GREEN = 255; - private static final int THUMB_BLUE = 240; - private static final int THUMB_WIDTH = 40; - private static final int THUMB_HEIGHT = 40; - private static final int THUMB_RADIUS = 20; - private static final int CONTROLLER_HIDE_DLEY_TIME = 5000; - private static final int PROGRESS_RUNNING_TIME = 1000; - private boolean isDragMode = false; - private Context context; - private ImplPlayer implPlayer; - private Image playToogle; - private Image imageForward; - private Image imageBackward; - private Slider progressBar; - private Text currentTime; - private Text totleTime; - private ControllerHandler controllerHandler; - private StatusChangeListener statusChangeListener = new StatusChangeListener() { - @Override - public void statusCallback(PlayerStatus status) { - context.getUITaskDispatcher().delayDispatch( - new Runnable() { - @Override - public void run() { - controllerHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING); - if (status == PlayerStatus.PREPARING) { - playToogle.setClickable(false); - progressBar.setEnabled(false); - progressBar.setProgressValue(0); - } else if (status == PlayerStatus.PREPARED) { - progressBar.setMaxValue(implPlayer.getAudioDuration()); - totleTime.setText(implPlayer.getDurationText()); - } else if (status == PlayerStatus.PLAY) { - controllerHandler.sendEvent( - Constants.PLAYER_PROGRESS_RUNNING, - EventHandler.Priority.IMMEDIATE); - playToogle.setPixelMap(ResourceTable.Media_ic_music_stop); - playToogle.setClickable(true); - progressBar.setEnabled(true); - } else if (status == PlayerStatus.PAUSE) { - controllerHandler.sendEvent( - Constants.PLAYER_PROGRESS_RUNNING, - EventHandler.Priority.IMMEDIATE); - playToogle.setPixelMap(ResourceTable.Media_ic_music_play); - } else if (status == PlayerStatus.STOP || status == PlayerStatus.COMPLETE) { - controllerHandler.sendEvent( - Constants.PLAYER_PROGRESS_RUNNING, - EventHandler.Priority.IMMEDIATE); - playToogle.setPixelMap(ResourceTable.Media_ic_update); - progressBar.setEnabled(false); - } else { - LogUtil.info(SimplePlayerController.class.getName(), "statuCallback else message"); - } - } - }, 0); - } - }; - - /** - * constructor of PlayerController - * - * @param context builder - * @param player player - */ - public SimplePlayerController(Context context, ImplPlayer player) { - super(context); - this.context = context; - implPlayer = player; - createHandler(); - initView(); - initListener(); - } - - private void createHandler() { - EventRunner runner = EventRunner.create(true); - if (runner == null) { - return; - } - controllerHandler = new ControllerHandler(runner); - } - - private void initView() { - Component playerController = LayoutScatter.getInstance(context).parse( - ResourceTable.Layout_simple_player_controller_layout, null, false); - addComponent(playerController); - if (playerController.findComponentById(ResourceTable.Id_play_controller) instanceof Image) { - playToogle = (Image) playerController.findComponentById(ResourceTable.Id_play_controller); - } - if (playerController.findComponentById(ResourceTable.Id_play_forward) instanceof Image) { - imageForward = (Image) playerController.findComponentById(ResourceTable.Id_play_forward); - } - if (playerController.findComponentById(ResourceTable.Id_play_backward) instanceof Image) { - imageBackward = (Image) playerController.findComponentById(ResourceTable.Id_play_backward); - } - if (playerController.findComponentById(ResourceTable.Id_progress) instanceof Slider) { - progressBar = (Slider) playerController.findComponentById(ResourceTable.Id_progress); - } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(THUMB_RED, THUMB_GREEN, THUMB_BLUE)); - shapeElement.setBounds(0, 0, THUMB_WIDTH, THUMB_HEIGHT); - shapeElement.setCornerRadius(THUMB_RADIUS); - progressBar.setThumbElement(shapeElement); - if (playerController.findComponentById(ResourceTable.Id_current_time) instanceof Text) { - currentTime = (Text) playerController.findComponentById(ResourceTable.Id_current_time); - } - if (playerController.findComponentById(ResourceTable.Id_end_time) instanceof Text) { - totleTime = (Text) playerController.findComponentById(ResourceTable.Id_end_time); - } - } - - private void initListener() { - implPlayer.addPlayerStatusCallback(statusChangeListener); - playToogle.setClickedListener(new ClickedListener() { - @Override - public void onClick(Component component) { - if (implPlayer.isPlaying()) { - implPlayer.pause(); - } else { - if (implPlayer.getPlayerStatus() == PlayerStatus.STOP) { - implPlayer.replay(); - } else { - implPlayer.resume(); - } - } - } - }); - imageForward.setClickedListener(new ClickedListener() { - @Override - public void onClick(Component component) { - implPlayer.rewindTo(implPlayer.getAudioCurrentPosition() + Constants.REWIND_STEP); - } - }); - imageBackward.setClickedListener(new ClickedListener() { - @Override - public void onClick(Component component) { - implPlayer.rewindTo(implPlayer.getAudioCurrentPosition() - Constants.REWIND_STEP); - } - }); - setValueChangedListener(); - } - - private void setValueChangedListener() { - progressBar.setValueChangedListener(new Slider.ValueChangedListener() { - @Override - public void onProgressUpdated(Slider slider, int value, boolean isB) { - context.getUITaskDispatcher().delayDispatch(new Runnable() { - @Override - public void run() { - currentTime.setText(DateUtils.msToString(value)); - } - }, 0); - } - - @Override - public void onTouchStart(Slider slider) { - isDragMode = true; - showController(false); - controllerHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING, EventHandler.Priority.IMMEDIATE); - } - - @Override - public void onTouchEnd(Slider slider) { - isDragMode = false; - if (slider.getProgress() == implPlayer.getAudioDuration()) { - implPlayer.stop(); - } else { - implPlayer.rewindTo(slider.getProgress()); - } - } - }); - } - - /** - * showController of PlayerController - * - * @param isAutoHide isAutoHide - */ - public void showController(boolean isAutoHide) { - controllerHandler.sendEvent(Constants.PLAYER_CONTROLLER_SHOW, EventHandler.Priority.HIGH); - if (isAutoHide) { - hideController(CONTROLLER_HIDE_DLEY_TIME); - } else { - controllerHandler.removeEvent(Constants.PLAYER_CONTROLLER_HIDE); - } - } - - /** - * hideController of PlayerController - * - * @param delay delay - */ - public void hideController(int delay) { - controllerHandler.removeEvent(Constants.PLAYER_CONTROLLER_HIDE); - controllerHandler.sendEvent(Constants.PLAYER_CONTROLLER_HIDE, delay, EventHandler.Priority.HIGH); - } - - /** - * ControllerHandler - * - * @since 2020-12-04 - */ - private class ControllerHandler extends EventHandler { - private ControllerHandler(EventRunner runner) { - super(runner); - } - - @Override - public void processEvent(InnerEvent event) { - super.processEvent(event); - if (event == null) { - return; - } - switch (event.eventId) { - case Constants.PLAYER_PROGRESS_RUNNING: - context.getUITaskDispatcher() - .delayDispatch( - new Runnable() { - @Override - public void run() { - progressBar.setProgressValue(implPlayer.getAudioCurrentPosition()); - currentTime.setText(implPlayer.getCurrentText()); - } - }, - 0); - if (implPlayer.isPlaying() && !isDragMode) { - controllerHandler.sendEvent( - Constants.PLAYER_PROGRESS_RUNNING, PROGRESS_RUNNING_TIME, Priority.IMMEDIATE); - } - break; - case Constants.PLAYER_CONTROLLER_HIDE: - context.getUITaskDispatcher() - .delayDispatch( - new Runnable() { - @Override - public void run() { - setVisibility(INVISIBLE); - } - }, - 0); - controllerHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING); - break; - case Constants.PLAYER_CONTROLLER_SHOW: - controllerHandler.sendEvent(Constants.PLAYER_PROGRESS_RUNNING, Priority.IMMEDIATE); - context.getUITaskDispatcher() - .delayDispatch( - new Runnable() { - @Override - public void run() { - setVisibility(VISIBLE); - } - }, - 0); - break; - default: - break; - } - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java deleted file mode 100644 index 503938d218672958baf91ba4a12986fd78867a41..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.constant; - -/** - * Constants - * - * @since 2020-12-04 - */ -public class Constants { - /** - * running - * - */ - public static final int PLAYER_PROGRESS_RUNNING = 0; - /** - * controller hide - * - */ - public static final int PLAYER_CONTROLLER_HIDE = 1; - /** - * controller show - * - */ - public static final int PLAYER_CONTROLLER_SHOW = 2; - /** - * 100 - * - */ - public static final int ONE_HUNDRED_PERCENT = 100; - /** - * rewind step - * - */ - public static final int REWIND_STEP = 5000; - /** - * volume step - * - */ - public static final int VOLUME_STEP = 5; - /** - * INTENT STARTTIME PARAM - */ - public static final String INTENT_STARTTIME_PARAM = "intetn_starttime_param"; - /** - * INTENT PLAYURL PARAM - */ - public static final String INTENT_PLAYURL_PARAM = "intetn_playurl_param"; - /** - * INTENT PLAYSTATU PARAM - */ - public static final String INTENT_PLAYSTATU_PARAM = "intetn_playstatu_param"; - - private Constants() { - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/ControlCode.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/ControlCode.java deleted file mode 100644 index 71284fbc9c44cc9dbd769135d6df69db85431c9f..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/ControlCode.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.constant; - -/** - * ControlCode enum - * - * @since 2020-12-04 - * - */ -public enum ControlCode { - /** - * resume to play the video when the video is paused - * - */ - RESUME(1001), - - /** - * pausethe video when the video is playing - * - */ - PAUSE(1002), - - /** - * pause the video when the video is playing - * - */ - STOP(1003), - - /** - * direct to the video - * - */ - SEEK(1004), - - /** - * forward the video-playing per second. - * - */ - FORWARD(1005), - - /** - * reduce the volume - * - */ - REWARD(1006), - - /** - * add the volume - * - */ - VOLUME_ADD(1007), - - /** - * reduce the volume - * - */ - VOLUME_REDUCED(1008), - - /** - * set volume - * - */ - VOLUME_SET(1009); - - private int code; - - ControlCode(int value) { - this.code = value; - } - - public int getCode() { - return code; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatus.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatus.java deleted file mode 100644 index a39e3c7e02469de6ec5b20c414fb5eea6cb82ea1..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatus.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.constant; - -/** - * PlayerStatus enum - * - * @since 2020-12-04 - * - */ -public enum PlayerStatus { - /** - * the video is released - * - */ - IDEL("idel"), - - /** - * video is preparing - * - */ - PREPARING("preparing"), - - /** - * when the video become prepared will be ready to play - * - */ - PREPARED("prepared"), - - /** - * start the video or resume to play - * - */ - PLAY("play"), - - /** - * pause the playing - * - */ - PAUSE("pause"), - - /** - * stop the playing - * - */ - STOP("stop"), - - /** - * the video play completed - * - */ - COMPLETE("complete"), - - /** - * the wrong status of video - * - */ - ERROR("error"), - - /** - * before the status of play - * - */ - BUFFERING("buffering"); - - private String status; - - PlayerStatus(String value) { - this.status = value; - } - - public String getStatus() { - return status; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java deleted file mode 100644 index 75d940c32a3dcff7170e91c858ccf52d78a2a681..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.factory; - -import com.huawei.codelab.util.LogUtil; -import ohos.app.Context; -import ohos.global.resource.RawFileDescriptor; -import ohos.media.common.Source; - -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.IOException; - -/** - * SourceFactory - * - * @since 2020-12-04 - * - */ -public class SourceFactory { - private static final String TAG = "SourceFactory"; - private static final String NET_HTTP_MATCH = "http"; - private static final String NET_RTMP_MATCH = "rtmp"; - private static final String NET_RTSP_MATCH = "rtsp"; - private static final String STORAGE_MATCH = "/storage/"; - - private Source mPlayerSource; - - /** - * constructor of SourceFactory - * - * @param context context - * @param path path - */ - public SourceFactory(Context context, String path) { - try { - initSourceType(context, path); - } catch (IOException e) { - LogUtil.error(TAG, "Audio resource is unavailable: "); - } - } - - private void initSourceType(Context context, String path) throws IOException { - if (context == null || path == null) { - return; - } - if (path.substring(0, NET_HTTP_MATCH.length()).equalsIgnoreCase(NET_HTTP_MATCH) - || path.substring(0, NET_RTMP_MATCH.length()).equalsIgnoreCase(NET_RTMP_MATCH) - || path.substring(0, NET_RTSP_MATCH.length()).equalsIgnoreCase(NET_RTSP_MATCH)) { - mPlayerSource = new Source(path); - } else if (path.startsWith(STORAGE_MATCH)) { - File file = new File(path); - if (file.exists()) { - FileInputStream fileInputStream = new FileInputStream(file); - FileDescriptor fileDescriptor = fileInputStream.getFD(); - mPlayerSource = new Source(fileDescriptor); - } - } else { - RawFileDescriptor fd = context.getResourceManager().getRawFileEntry(path).openRawFileDescriptor(); - mPlayerSource = new Source(fd.getFileDescriptor(), fd.getStartPosition(), fd.getFileSize()); - } - } - - /** - * getSource of Source - * - * @return Source - */ - public Source getSource() { - return mPlayerSource; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java deleted file mode 100644 index ff8065ddb36f1f4af40e7a29b5b82bf485d0ae42..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.manager; - -import com.huawei.codelab.player.api.ImplLifecycle; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.util.LogUtil; - -/** - * HmPlayerLifecycle - * - * @since 2020-12-04 - */ -public class HmPlayerLifecycle implements ImplLifecycle { - private static final String TAG = HmPlayerLifecycle.class.getSimpleName(); - private ImplPlayer player; - private boolean isBackGround; - - /** - * constructor of HmPlayerLifecycle - * - * @param player player - */ - public HmPlayerLifecycle(ImplPlayer player) { - this.player = player; - } - - @Override - public void onStart() { - } - - @Override - public void onForeground() { - if (isBackGround) { - String url = player.getBuilder().getFilePath(); - int startTime = player.getBuilder().getStartMillisecond(); - player.reload(url, startTime); - isBackGround = false; - } - } - - @Override - public void onBackground() { - if (!isBackGround) { - LogUtil.info(TAG, "onBackground is called ,palyer statu is " + player.getPlayerStatus().getStatus()); - player.getBuilder().setPause(player.getPlayerStatus() == PlayerStatus.PAUSE); - player.getBuilder().setFilePath(player.getBuilder().getFilePath()); - player.getBuilder().setStartMillisecond(player.getAudioCurrentPosition()); - player.release(); - isBackGround = true; - } - } - - @Override - public void onStop() { - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/AdvertisementProvider.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/AdvertisementProvider.java deleted file mode 100644 index bff28e76b3733bb80b9c3fa4c78f6fd0c03b9f17..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/AdvertisementProvider.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.provider; - -import ohos.agp.components.Component; -import ohos.agp.components.ComponentContainer; -import ohos.agp.components.PageSliderProvider; - -import java.util.List; - -/** - * Advertising display adapter - * - * @param type - * @since 2020-12-04 - */ -public class AdvertisementProvider extends PageSliderProvider { - private List componentList; - - /** - * constructor - * - * @param componentList component list - */ - public AdvertisementProvider(List componentList) { - this.componentList = componentList; - } - - /** - * get count - * - * @return int - */ - public int getCount() { - return componentList.size(); - } - - @Override - public Object createPageInContainer(ComponentContainer componentContainer, int index) { - componentContainer.addComponent(componentList.get(index)); - return componentList.get(index); - } - - @Override - public void destroyPageFromContainer(ComponentContainer componentContainer, int index, Object obj) { - componentContainer.removeComponent(componentList.get(index)); - } - - @Override - public boolean isPageMatchToObject(Component component, Object obj) { - return component == obj; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/CommonProvider.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/CommonProvider.java deleted file mode 100644 index dd851b146a7cc00d5c88000987eb62f84a7fa2d0..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/CommonProvider.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.provider; - -import ohos.agp.components.BaseItemProvider; -import ohos.agp.components.Component; -import ohos.agp.components.ComponentContainer; -import ohos.app.Context; - -import java.util.ArrayList; -import java.util.List; - -/** - * CommonAdapter - * - * @param type - * @since 2020-12-04 - */ -public abstract class CommonProvider extends BaseItemProvider { - /** - * source list - */ - protected List datas; - /** - * context - */ - protected Context context; - /** - * the resource id - */ - protected int layoutId; - - /** - * constructor of CommonAdapter - * - * @param context context - * @param layoutId id - */ - public CommonProvider(Context context, final int layoutId) { - this(new ArrayList(0), context, layoutId); - } - - /** - * constructor of CommonAdapter - * - * @param context context - * @param layoutId id - * @param datas listContainer data - */ - public CommonProvider(List datas, Context context, int layoutId) { - this.datas = datas; - this.context = context; - this.layoutId = layoutId; - } - - @Override - public int getCount() { - return datas != null ? datas.size() : 0; - } - - /** - * return data - * - * @param position position - * @return data - */ - @Override - public T getItem(int position) { - return datas.get(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public Component getComponent(int position, Component component, ComponentContainer parent) { - ViewProvider holder = ViewProvider.get(context, component, parent, layoutId, position); - - convert(holder, getItem(position), position); - return holder.getComponentView(); - } - - /** - * convert to a new Collection,contains clear it - * - * @param holder holder - * @param item item - * @param position position - */ - protected abstract void convert(ViewProvider holder, T item, int position); -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/ViewProvider.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/ViewProvider.java deleted file mode 100644 index 7ce1e836456548dbc5c0e03ad7070da778151c53..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/provider/ViewProvider.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.provider; - -import ohos.agp.components.Component; -import ohos.agp.components.ComponentContainer; -import ohos.agp.components.Image; -import ohos.agp.components.LayoutScatter; -import ohos.agp.components.Text; -import ohos.app.Context; - -import java.util.HashMap; - -/** - * ViewProvider - * - * @since 2020-12-04 - * - */ -public class ViewProvider { - /** - * set Position - */ - protected int componentPosition; - /** - * set layout id - */ - protected int layoutId; - private Component component; - private Context context; - private HashMap views; - - /** - * constructor of ViewProvider - * - * @param context context - * @param itemView itemView - * @param parent parent - * @param position position - */ - public ViewProvider(Context context, Component itemView, ComponentContainer parent, int position) { - this.context = context; - component = itemView; - this.componentPosition = position; - views = new HashMap(0); - component.setTag(this); - } - - /** - * constructor of ViewProvider - * - * @param context context - * @param convertView convertView - * @param parent parent - * @param layoutId layoutId - * @param position position - * @return ViewProvider - */ - public static ViewProvider get(Context context, Component convertView, ComponentContainer parent, - int layoutId, int position) { - if (convertView == null) { - Component itemView = LayoutScatter.getInstance(context).parse(layoutId, null, false); - ViewProvider viewProvider = new ViewProvider(context, itemView, parent, position); - viewProvider.layoutId = layoutId; - return viewProvider; - } else { - ViewProvider viewProvider = null; - Object object = convertView.getTag(); - if (object instanceof ViewProvider) { - viewProvider = (ViewProvider) object; - viewProvider.componentPosition = position; - } - return viewProvider; - } - } - - /** - * Get the control by viewId - * - * @param viewId viewId - * @param generic - * @return view - */ - @SuppressWarnings("unchecked") - public T getView(int viewId) { - Component view = views.get(viewId); - if (view == null) { - view = component.findComponentById(viewId); - views.put(viewId, view); - } - return (T) view; - } - - /** - * return Component - * - * @return Component - */ - public Component getComponentView() { - return component; - } - - /** - * get layout id - * - * @return xmlId - */ - public int getLayoutId() { - return layoutId; - } - - /** - * update pointer - * - * @param position position - */ - public void updatePosition(int position) { - this.componentPosition = position; - } - - /** - * get item position - * - * @return int - */ - public int getItemPosition() { - return componentPosition; - } - - /** - * set text - * - * @param viewId viewId - * @param text text - * @return ViewProvider - */ - public ViewProvider setText(int viewId, String text) { - Text tv = getView(viewId); - tv.setText(text); - return this; - } - - /** - * set image - * - * @param viewId viewId - * @param resId ImageResource - * @return ViewProvider - */ - public ViewProvider setImageResource(int viewId, int resId) { - Image image = getView(viewId); - image.setPixelMap(resId); - image.setScaleMode(Image.ScaleMode.STRETCH); - return this; - } - - /** - * set onClick Listener - * - * @param viewId viewId - * @param listener listener - * @return ViewProvider - */ - public ViewProvider setOnClickListener(int viewId, Component.ClickedListener listener) { - Component newComponent = getView(viewId); - newComponent.setClickedListener(listener); - return this; - } - - /** - * set OnTouch Listener - * - * @param viewId viewId - * @param listener listener - * @return ViewProvider - */ - public ViewProvider setOnTouchListener(int viewId, Component.TouchEventListener listener) { - Component newComponent = getView(viewId); - newComponent.setTouchEventListener(listener); - return this; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java deleted file mode 100644 index 087b264a7e2c0e6974209702f01079b1fda291b5..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.slice; - -import com.huawei.codelab.MainAbility; -import com.huawei.codelab.data.AdvertisementMo; -import com.huawei.codelab.data.VideoListMo; -import com.huawei.codelab.data.VideoTabStyle; -import com.huawei.codelab.provider.AdvertisementProvider; -import com.huawei.codelab.provider.CommonProvider; -import com.huawei.codelab.provider.ViewProvider; -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.util.LogUtil; -import com.huawei.codelab.util.MediaUtil; -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.content.Intent; -import ohos.aafwk.content.Operation; -import ohos.agp.colors.RgbColor; - -import ohos.agp.components.element.ShapeElement; -import ohos.agp.text.Font; -import ohos.agp.utils.Color; -import ohos.agp.components.Component; -import ohos.agp.components.Image; -import ohos.agp.components.LayoutScatter; -import ohos.agp.components.ListContainer; -import ohos.agp.components.PageSlider; -import ohos.agp.components.PageSliderIndicator; -import ohos.agp.components.Text; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * the main page - * - * @since 2020-12-04 - * - */ -public class MainAbilitySlice extends AbilitySlice { - private static final String TAG = MainAbility.class.getSimpleName(); - private static final String INTENT_STARTTIME_PARAM = "intetn_starttime_param"; - private CommonProvider commonProvider; - private AdvertisementProvider advertisementProvider; - private PageSlider advPageSlider; - private ScheduledExecutorService scheduledExecutor; - private int currentPageIndex = 0; - private Runnable slidTask; - - @Override - protected void onStart(Intent intent) { - super.onStart(intent); - setUIContent(ResourceTable.Layout_video); - initContent(); - } - - private void initContent() { - initScheduledExecutor(); - initAdvertisement(); - initList(); - startSlidTimer(); - } - - private void initScheduledExecutor() { - slidTask = () -> getUITaskDispatcher().asyncDispatch(() -> { - if (currentPageIndex == advertisementProvider.getCount()) { - currentPageIndex = 0; - } else { - currentPageIndex++; - } - advPageSlider.setCurrentPage(currentPageIndex); }); - scheduledExecutor = new ScheduledThreadPoolExecutor(1); - } - - private void initList() { - LogUtil.info(TAG, "begin updateTableView tab view"); - Text playTitle = null; - if (findComponentById(ResourceTable.Id_video_play_title) instanceof Text) { - playTitle = (Text) findComponentById(ResourceTable.Id_video_play_title); - } - Font.Builder fb = new Font.Builder(VideoTabStyle.BOLD_FONT_NAME); - fb.setWeight(Font.BOLD); - Font newFont = fb.build(); - playTitle.setFont(newFont); - commonProvider = new CommonProvider(MediaUtil.getPlayListMos(), getContext(), - ResourceTable.Layout_recommend_gv_item) { - @Override - protected void convert(ViewProvider viewProvider, VideoListMo item, int position) { - viewProvider.setText(ResourceTable.Id_name_tv, item.getName()); - viewProvider.setText(ResourceTable.Id_content_tv, item.getDescription()); - viewProvider.setImageResource(ResourceTable.Id_image_iv, item.getSourceId()); - } - }; - ListContainer playListContainer = null; - if (findComponentById(ResourceTable.Id_video_list_play_view) instanceof ListContainer) { - playListContainer = (ListContainer) findComponentById(ResourceTable.Id_video_list_play_view); - } - playListContainer.setItemProvider(commonProvider); - playListContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { - @Override - public void onItemClicked(ListContainer listContainer, Component component, int i, long l) { - startFa(); - } - }); - } - - private void initAdvertisement() { - advertisementProvider = new AdvertisementProvider(getAdvertisementComponents()); - Component advViewPager = findComponentById(ResourceTable.Id_video_advertisement_viewpager); - if (advViewPager instanceof PageSlider) { - advPageSlider = (PageSlider) advViewPager; - advPageSlider.setProvider(advertisementProvider); - advPageSlider.setClickedListener(component -> { - startFa(); - }); - } else { - LogUtil.debug(TAG, "initAdvertisement failed, advertisement_viewpager is not PageSlider"); - } - PageSliderIndicator advIndicator = null; - if (findComponentById(ResourceTable.Id_video_advertisement_indicator) instanceof PageSliderIndicator) { - advIndicator = (PageSliderIndicator) findComponentById( - ResourceTable.Id_video_advertisement_indicator); - } - advIndicator.setItemOffset(VideoTabStyle.INDICATOR_OFFSET); - ShapeElement normalDrawable = new ShapeElement(); - normalDrawable.setRgbColor(RgbColor.fromRgbaInt(Color.WHITE.getValue())); - normalDrawable.setAlpha(VideoTabStyle.INDICATOR_NORMA_ALPHA); - normalDrawable.setShape(ShapeElement.OVAL); - normalDrawable.setBounds(0, 0, VideoTabStyle.INDICATOR_BONDS, VideoTabStyle.INDICATOR_BONDS); - ShapeElement selectedDrawable = new ShapeElement(); - selectedDrawable.setRgbColor(RgbColor.fromRgbaInt(Color.WHITE.getValue())); - selectedDrawable.setShape(ShapeElement.OVAL); - selectedDrawable.setBounds(0, 0, VideoTabStyle.INDICATOR_BONDS, VideoTabStyle.INDICATOR_BONDS); - advIndicator.setItemElement(normalDrawable, selectedDrawable); - advIndicator.setViewPager((PageSlider) advViewPager); - } - - private void startFa() { - Intent intent = new Intent(); - Operation operation = new Intent.OperationBuilder().withBundleName(getBundleName()) - .withAbilityName("com.huawei.codelab.MainAbility").withAction("action.video.play").build(); - intent.setOperation(operation); - intent.setParam(INTENT_STARTTIME_PARAM, 0); - startAbility(intent); - } - - private List getAdvertisementComponents() { - List advertisementMos = MediaUtil.getVideoAdvertisementInfo(); - List componentList = new ArrayList<>(advertisementMos.size()); - Font.Builder fb = new Font.Builder(VideoTabStyle.BOLD_FONT_NAME); - fb.setWeight(Font.BOLD); - Font newFont = fb.build(); - for (AdvertisementMo advertisementMo : advertisementMos) { - Component advRootView = LayoutScatter.getInstance(getContext()).parse( - ResourceTable.Layout_video_advertisement_item, null, false); - Image imgTemp = null; - if (advRootView.findComponentById(ResourceTable.Id_video_advertisement_poster) instanceof Image) { - imgTemp = (Image) advRootView.findComponentById(ResourceTable.Id_video_advertisement_poster); - } - imgTemp.setPixelMap(advertisementMo.getSourceId()); - Text titleTmp = null; - if (advRootView.findComponentById(ResourceTable.Id_video_advertisement_title) instanceof Text) { - titleTmp = (Text) advRootView.findComponentById(ResourceTable.Id_video_advertisement_title); - } - titleTmp.setText(advertisementMo.getDescription()); - titleTmp.setFont(newFont); - componentList.add(advRootView); - } - - return componentList; - } - - private void startSlidTimer() { - scheduledExecutor.scheduleAtFixedRate(slidTask, VideoTabStyle.ADVERTISEMENT_SLID_PROID, - VideoTabStyle.ADVERTISEMENT_SLID_DELAY, TimeUnit.SECONDS); - } - - @Override - public void onActive() { - super.onActive(); - } - - @Override - public void onInactive() { - super.onInactive(); - LogUtil.info(TAG, "is onInactive"); - } - - @Override - public void onForeground(Intent intent) { - super.onForeground(intent); - LogUtil.info(TAG, "is onForeground"); - } - - @Override - public void onBackground() { - super.onBackground(); - LogUtil.info(TAG, "is onBackground"); - } - - @Override - public void onStop() { - super.onStop(); - LogUtil.info(TAG, "is onStop"); - } - - @Override - protected void onBackPressed() { - LogUtil.info(TAG, "is onBackPressed"); - super.onBackPressed(); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java deleted file mode 100644 index 9a9673273bb22d3d94a3da83e7ce1ef8299cb435..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.slice; - -import com.huawei.codelab.VideoMigrateService; -import com.huawei.codelab.manager.ImplVideoMigration; -import com.huawei.codelab.manager.VideoMigrationStub; -import com.huawei.codelab.provider.CommonProvider; -import com.huawei.codelab.provider.ViewProvider; -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.component.RemoteController; -import com.huawei.codelab.component.SlidePopupWindow; -import com.huawei.codelab.component.Toast; -import com.huawei.codelab.player.HmPlayer; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.PlayerStatus; -import com.huawei.codelab.player.component.PlayerLoading; -import com.huawei.codelab.player.component.SimplePlayerController; -import com.huawei.codelab.util.AbilitySliceRouteUtil; -import com.huawei.codelab.util.LogUtil; -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.ability.IAbilityConnection; -import ohos.aafwk.content.Intent; -import ohos.aafwk.content.Operation; -import ohos.agp.components.Component; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.Image; -import ohos.agp.components.ListContainer; -import ohos.bundle.ElementName; -import ohos.distributedschedule.interwork.DeviceInfo; -import ohos.distributedschedule.interwork.DeviceManager; -import ohos.rpc.IRemoteObject; -import ohos.rpc.RemoteException; - -import java.util.ArrayList; -import java.util.List; - -/** - * PlayerAbilitySlice - * - * @since 2020-12-04 - */ -public class SimplePlayerAbilitySlice extends AbilitySlice { - private static final String TAG = SimplePlayerAbilitySlice.class.getSimpleName(); - private static final int TOAST_DURATION = 3000; - private static ImplPlayer implPlayer; - private RemoteController remoteController; - private ImplVideoMigration implVideoMigration; - private ListContainer deviceListContainer; - private Image tv; - private SlidePopupWindow transWindow; - private List devices = new ArrayList<>(0); - private int startMillisecond; - //private String url = "entry/resources/base/media/202011060201.mp4"; - private String url = "entry/resources/base/media/gubeishuizhen.mp4"; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_simple_video_play_layout); - startMillisecond = intent.getIntParam(Constants.INTENT_STARTTIME_PARAM, 0); - initComponent(); - initListener(); - implPlayer.getLifecycle().onStart(); - } - - public static ImplPlayer getImplPlayer() { - return implPlayer; - } - - private void initComponent() { - DependentLayout layout = null; - if (findComponentById(ResourceTable.Id_parent) instanceof DependentLayout) { - layout = (DependentLayout) findComponentById(ResourceTable.Id_parent); - } - transWindow = new SlidePopupWindow(this, ResourceTable.Layout_trans_slide); - remoteController = new RemoteController(this); - layout.addComponent(transWindow); - layout.addComponent(remoteController); - if (transWindow.findComponentById(ResourceTable.Id_device_list_container) instanceof ListContainer) { - deviceListContainer = (ListContainer) transWindow.findComponentById(ResourceTable.Id_device_list_container); - } - DependentLayout playerLayout = null; - if (findComponentById(ResourceTable.Id_parent_layout) instanceof DependentLayout) { - playerLayout = (DependentLayout) findComponentById(ResourceTable.Id_parent_layout); - } - implPlayer = new HmPlayer.Builder(this).setStartMillisecond(startMillisecond).setFilePath(url).create(); - SimplePlayerController simplePlayerController = new SimplePlayerController(this, implPlayer); - if (simplePlayerController.findComponentById(ResourceTable.Id_tv) instanceof Image) { - tv = (Image) simplePlayerController.findComponentById(ResourceTable.Id_tv); - } - PlayerLoading playerLoading = new PlayerLoading(this, implPlayer); - playerLayout.addComponent(implPlayer.getPlayerView()); - playerLayout.addComponent(playerLoading); - playerLayout.addComponent(simplePlayerController); - implPlayer.play(); - } - - private void initListener() { - tv.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - initDevices(); - showDeviceList(); - } - }); - deviceListContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { - @Override - public void onItemClicked(ListContainer listContainer, Component component, int num, long l) { - transWindow.hide(); - startAbilityFa(devices.get(num).getDeviceId()); - } - }); - transWindow.setPopupWindowListener(new SlidePopupWindow.PopupWindowListener() { - @Override - public void windowShow() { - implPlayer.pause(); - } - - @Override - public void windowDismiss() { - if (implPlayer.getPlayerStatus() == PlayerStatus.PAUSE) { - implPlayer.resume(); - } - } - }); - setRemoteControllerCallback(); - } - - private void setRemoteControllerCallback() { - remoteController.setRemoteControllerCallback(new RemoteController.RemoteControllerListener() { - @Override - public void controllerShow() { - } - - @Override - public void controllerDismiss() { - int progress = 0; - try { - if (implVideoMigration != null) { - progress = implVideoMigration.flyOut(); - } - } catch (RemoteException e) { - LogUtil.error(TAG, "RemoteException occurs"); - } - implPlayer.reload(url, progress); - } - - @Override - public void sendControl(int code, int extra) { - try { - if (implVideoMigration != null) { - implVideoMigration.playControl(code, extra); - } - } catch (RemoteException e) { - LogUtil.error(TAG, "RemoteException occurs "); - } - } - }); - } - - private void initDevices() { - if (devices.size() > 0) { - devices.clear(); - } - List deviceInfos = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE); - devices.addAll(deviceInfos); - } - - private void showDeviceList() { - CommonProvider commonProvider = new CommonProvider(devices, getContext(), - ResourceTable.Layout_device_list_item) { - @Override - protected void convert(ViewProvider viewProvider, DeviceInfo item, int position) { - viewProvider.setText(ResourceTable.Id_device_text, item.getDeviceName()); - } - }; - deviceListContainer.setItemProvider(commonProvider); - commonProvider.notifyDataChanged(); - transWindow.show(); - } - - private void startAbilityFa(String devicesId) { - Intent intent = new Intent(); - Operation operation = - new Intent.OperationBuilder() - .withDeviceId(devicesId) - .withBundleName(getBundleName()) - .withAbilityName(VideoMigrateService.class.getName()) - .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) - .build(); - intent.setOperation(operation); - boolean connectFlag = connectAbility(intent, new IAbilityConnection() { - @Override - public void onAbilityConnectDone(ElementName elementName, IRemoteObject remoteObject, int i) { - implVideoMigration = VideoMigrationStub.asInterface(remoteObject); - try { - implVideoMigration.flyIn(startMillisecond); - } catch (RemoteException e) { - LogUtil.error(TAG, "connect successful,but have remote exception"); - } - } - - @Override - public void onAbilityDisconnectDone(ElementName elementName, int i) { - disconnectAbility(this); - } - }); - if (connectFlag) { - Toast.toast(this, "transmit successful!", TOAST_DURATION); - remoteController.show(); - startMillisecond = implPlayer.getAudioCurrentPosition(); - implPlayer.release(); - } else { - Toast.toast(this, "transmit failed!Please try again later.", TOAST_DURATION); - } - } - - @Override - public void onActive() { - super.onActive(); - AbilitySliceRouteUtil.getInstance().addRoute(this); - } - - @Override - protected void onInactive() { - LogUtil.info(TAG, "onInactive is called"); - super.onInactive(); - } - - @Override - public void onForeground(Intent intent) { - if (remoteController == null || !remoteController.isShown()) { - implPlayer.getLifecycle().onForeground(); - } - super.onForeground(intent); - } - - @Override - protected void onBackground() { - LogUtil.info(TAG, "onBackground is called"); - if (remoteController == null || !remoteController.isShown()) { - implPlayer.getLifecycle().onBackground(); - } - super.onBackground(); - } - - @Override - protected void onBackPressed() { - if (remoteController != null && remoteController.isShown()) { - remoteController.hide(); - } else { - super.onBackPressed(); - } - } - - @Override - protected void onStop() { - LogUtil.info(TAG, "onStop is called"); - AbilitySliceRouteUtil.getInstance().removeRoute(this); - implPlayer.getLifecycle().onStop(); - super.onStop(); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/AbilitySliceRouteUtil.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/AbilitySliceRouteUtil.java deleted file mode 100644 index 12838b43a3460bd748c9a256e3cdfd264eb68a0a..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/AbilitySliceRouteUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import ohos.aafwk.ability.AbilitySlice; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * AbilitySliceRoute util - * - * @since 2020-12-04 - * - */ -public class AbilitySliceRouteUtil { - private static AbilitySliceRouteUtil instance; - - private List> routes; - - private AbilitySliceRouteUtil() { - routes = new ArrayList<>(0); - } - - /** - * initialization AbilitySliceRouteUtil - * - * @return AbilitySliceRouteUtil - */ - public static synchronized AbilitySliceRouteUtil getInstance() { - if (instance == null) { - instance = new AbilitySliceRouteUtil(); - } - return instance; - } - - /** - * add route - * - * @param slice slice - */ - public void addRoute(AbilitySlice slice) { - Map map = new HashMap<>(0); - map.put(slice.getClass().getName(), slice); - routes.add(map); - } - - /** - * remove Route - * - * @param slice slice - */ - public void removeRoute(AbilitySlice slice) { - String tag = slice.getClass().getName(); - for (int i = routes.size() - 1; i >= 0; i--) { - for (Map.Entry stringAbilitySliceEntry : routes.get(i).entrySet()) { - String key = null; - if (stringAbilitySliceEntry instanceof Map.Entry) { - if (((Map.Entry) stringAbilitySliceEntry).getKey() instanceof String) { - key = (String) ((Map.Entry) stringAbilitySliceEntry).getKey(); - } - } - if (tag.equals(key)) { - routes.remove(routes.get(i)); - break; - } - } - } - } - - /** - * terminateAbilitySlice method - */ - public void terminateAbilitySlice() { - for (int i = routes.size() - 1; i >= 0; i--) { - for (Map.Entry stringAbilitySliceEntry : routes.get(i).entrySet()) { - if (stringAbilitySliceEntry instanceof Map.Entry) { - if (((Map.Entry) stringAbilitySliceEntry).getValue() instanceof AbilitySlice) { - AbilitySlice abilitySlice = (AbilitySlice) ((Map.Entry) stringAbilitySliceEntry).getValue(); - abilitySlice.terminate(); - } - } - } - } - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/DateUtils.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/DateUtils.java deleted file mode 100644 index b18a33804a3a4d49a2c26f5a985300972847a6ee..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/DateUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import java.util.Locale; - -/** - * Date util - * - * @since 2020-12-04 - * - */ -public class DateUtils { - private static final int ONE_SECONDS_MS = 1000; - private static final int ONE_MINS_MINUTES = 60; - private static final int NUMBER = 16; - private static final String TIME_FORMAT = "%02d"; - private static final String SEMICOLON = ":"; - - private DateUtils() { - } - - /** - * conversion of msToString - * - * @param ms ms - * @return string - */ - public static String msToString(int ms) { - StringBuilder sb = new StringBuilder(NUMBER); - int seconds = ms / ONE_SECONDS_MS; - int minutes = seconds / ONE_MINS_MINUTES; - if (minutes > ONE_MINS_MINUTES) { - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes / ONE_MINS_MINUTES)); - sb.append(SEMICOLON); - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes % ONE_MINS_MINUTES)); - sb.append(SEMICOLON); - } else { - sb.append("00:"); - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes)); - sb.append(SEMICOLON); - } - - if (seconds > minutes * ONE_MINS_MINUTES) { - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, seconds - minutes * ONE_MINS_MINUTES)); - } else { - sb.append("00"); - } - return sb.toString(); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java deleted file mode 100644 index 74b35a784b6bfec3c225299e3b2baf559fa3713e..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; - -/** - * Log util - * - * @since 2020-12-04 - * - */ -public class LogUtil { - private static final String TAG_LOG = "LogUtil"; - - private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtil.TAG_LOG); - - private static final String LOG_FORMAT = "%{public}s: %{public}s"; - - private LogUtil() { - } - - /** - * Print debug log - * - * @param tag log tag - * @param msg log message - */ - public static void debug(String tag, String msg) { - HiLog.debug(LABEL_LOG, LOG_FORMAT, tag, msg); - } - - /** - * Print info log - * - * @param tag log tag - * @param msg log message - */ - public static void info(String tag, String msg) { - HiLog.info(LABEL_LOG, LOG_FORMAT, tag, msg); - } - - /** - * Print error log - * - * @param tag log tag - * @param msg log message - */ - public static void error(String tag, String msg) { - HiLog.error(LABEL_LOG, LOG_FORMAT, tag, msg); - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/MediaUtil.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/MediaUtil.java deleted file mode 100644 index 272623d8bfa6bb226e251bafc7178b746b097350..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/MediaUtil.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import com.huawei.codelab.data.AdvertisementMo; -import com.huawei.codelab.data.VideoListMo; -import com.huawei.codelab.ResourceTable; - -import java.util.ArrayList; -import java.util.List; - -/** - * Media util - * - * @since 2020-12-04 - * - */ -public class MediaUtil { - private static List videoAdvertisementMos = new ArrayList<>(0); - private static List playListMos = new ArrayList<>(0); - - private MediaUtil() { - } - - static { - videoAdvertisementMos.add(new AdvertisementMo(ResourceTable.Media_video_ad0,"green")); - videoAdvertisementMos.add(new AdvertisementMo(ResourceTable.Media_video_ad2,"yellow")); - videoAdvertisementMos.add(new AdvertisementMo(ResourceTable.Media_video_ad3,"red")); - playListMos.add(new VideoListMo(ResourceTable.Media_video_list0, - "landscape", "waterfall")); - playListMos.add(new VideoListMo(ResourceTable.Media_video_list2, "child", "cute")); - playListMos.add(new VideoListMo(ResourceTable.Media_video_list1, "show", "drone")); - } - - /** - * get the advertisement constructor - * - * @return advertisementMos - */ - public static List getVideoAdvertisementInfo() { - return videoAdvertisementMos; - } - - /** - * get VideoListMos - * - * @return VideoListMo - */ - public static List getPlayListMos() { - return playListMos; - } -} diff --git a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java b/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java deleted file mode 100644 index a6c05cebf242fcbed7684eb46c68372b47bf3ae9..0000000000000000000000000000000000000000 --- a/DistributedVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import ohos.agp.utils.Point; -import ohos.agp.window.service.Display; -import ohos.agp.window.service.DisplayManager; -import ohos.app.Context; - -import java.util.Optional; - -/** - * Component component maker - * - * @since 2020-12-04 - * - */ -public class ScreenUtils { - private ScreenUtils() { - // Do nothing - } - - /** - * getScreenHeight - * - * @param context context - * @return int - */ - public static int getScreenHeight(Context context) { - DisplayManager displayManager = DisplayManager.getInstance(); - Optional optDisplay = displayManager.getDefaultDisplay(context); - Point point = new Point(0, 0); - if (!optDisplay.isPresent()) { - return (int) point.position[1]; - } else { - Display display = optDisplay.get(); - display.getSize(point); - return (int) point.position[1]; - } - } - - /** - * getScreenWidth - * - * @param context context - * @return int - */ - public static int getScreenWidth(Context context) { - DisplayManager displayManager = DisplayManager.getInstance(); - Optional optDisplay = displayManager.getDefaultDisplay(context); - Point point = new Point(0, 0); - if (!optDisplay.isPresent()) { - return (int) point.position[0]; - } else { - Display display = optDisplay.get(); - display.getSize(point); - return (int) point.position[0]; - } - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java deleted file mode 100644 index 7beede00789c2747b217e77ac65d918d973e682b..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/MainAbility.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab; - -import com.huawei.codelab.slice.SimplePlayerAbilitySlice; - -import ohos.aafwk.ability.Ability; -import ohos.aafwk.content.Intent; - -/** - * the main page - * - * @since 2021-04-04 - * - */ -public class MainAbility extends Ability { - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setMainRoute(SimplePlayerAbilitySlice.class.getName()); - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java deleted file mode 100644 index 6fd3e96c71bf0f0426e3c4111be56eb9c4e2a39e..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/HmPlayer.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player; - -import com.huawei.codelab.player.api.ImplLifecycle; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.api.ScreenChangeListener; -import com.huawei.codelab.player.api.StatuChangeListener; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.PlayerStatu; -import com.huawei.codelab.player.factory.SourceFactory; -import com.huawei.codelab.player.manager.HmPlayerLifecycle; -import com.huawei.codelab.util.LogUtil; - -import ohos.agp.graphics.Surface; -import ohos.app.Context; -import ohos.app.dispatcher.task.TaskPriority; -import ohos.media.common.Source; -import ohos.media.player.Player; - -import java.util.ArrayList; -import java.util.List; - -/** - * Hm player - * - * @since 2021-04-04 - */ -public class HmPlayer implements ImplPlayer { - private static final String TAG = HmPlayer.class.getSimpleName(); - private static final int MICRO_MILLI_RATE = 1000; - private Player mPlayer; - private Surface surface; - private HmPlayerLifecycle mLifecycle; - private Builder mBuilder; - private PlayerStatu mStatu = PlayerStatu.IDEL; - private float currentVolume = 1; - private double videoScale = Constants.NUMBER_NEGATIVE_1; - private boolean isGestureOpen; - - private List statuChangeCallbacks = new ArrayList<>(0); - private List screenChangeCallbacks = new ArrayList<>(0); - - /** - * constructor of HmPlayer - * - * @param builder builder - */ - private HmPlayer(Builder builder) { - mBuilder = builder; - mLifecycle = new HmPlayerLifecycle(this); - } - - private void initBasePlayer() { - mPlayer = new Player(mBuilder.mContext); - Source source = new SourceFactory(mBuilder.mContext, mBuilder.filePath).getSource(); - mPlayer.setSource(source); - mPlayer.setPlayerCallback(new HmPlayerCallback()); - } - - /** - * HmPlayer Callback - * - * @since 2020-12-04 - */ - private class HmPlayerCallback implements Player.IPlayerCallback { - @Override - public void onPrepared() { - LogUtil.info(TAG, "onPrepared is called "); - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PREPARED; - callback.statuCallback(PlayerStatu.PREPARED); - } - } - - @Override - public void onMessage(int info, int i1) { - LogUtil.info(TAG, "onMessage info is " + info + ",i1 is" + i1); - if (i1 == 0) { - switch (info) { - case Player.PLAYER_INFO_VIDEO_RENDERING_START: - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PLAY; - callback.statuCallback(PlayerStatu.PLAY); - } - if (mBuilder.isPause) { - pause(); - } - break; - case Player.PLAYER_INFO_BUFFERING_START: - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.BUFFERING; - callback.statuCallback(PlayerStatu.BUFFERING); - } - break; - case Player.PLAYER_INFO_BUFFERING_END: - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PLAY; - callback.statuCallback(PlayerStatu.PLAY); - } - break; - default: - break; - } - } - } - - @Override - public void onError(int type, int extra) { - LogUtil.info(TAG, "onError is called ,i is " + type + ",i1 is " + extra); - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.ERROR; - callback.statuCallback(PlayerStatu.ERROR); - } - release(); - } - - @Override - public void onResolutionChanged(int videoX, int videoY) { - LogUtil.info(TAG, "onResolutionChanged videoX is " + videoX + ",videoY is " + videoY); - if (!mBuilder.isStretch && videoX != 0 && videoY != 0) { - videoScale = (double) videoX / videoY; - } - } - - @Override - public void onPlayBackComplete() { - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.COMPLETE; - callback.statuCallback(PlayerStatu.COMPLETE); - } - } - - @Override - public void onRewindToComplete() { - resume(); - } - - @Override - public void onBufferingChange(int value) { - } - - @Override - public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) { - LogUtil.info(TAG, "onNewTimedMetaData is called"); - } - - @Override - public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) { - LogUtil.info(TAG, "onMediaTimeIncontinuity is called"); - for (Player.StreamInfo streanInfo : mPlayer.getStreamInfo()) { - int streamType = streanInfo.getStreamType(); - if (streamType == Player.StreamInfo.MEDIA_STREAM_TYPE_AUDIO && mStatu == PlayerStatu.PREPARED) { - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PLAY; - callback.statuCallback(PlayerStatu.PLAY); - } - if (mBuilder.isPause) { - pause(); - } - } - } - } - } - - /** - * start time consuming operation - */ - private void start() { - if (mPlayer != null) { - mBuilder.mContext.getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> { - if (surface != null) { - mPlayer.setVideoSurface(surface); - } else { - LogUtil.error(TAG, "The surface has not been initialized."); - } - mPlayer.prepare(); - if (mBuilder.startMillisecond > 0) { - int microsecond = mBuilder.startMillisecond * MICRO_MILLI_RATE; - mPlayer.rewindTo(microsecond); - } - mPlayer.play(); - }); - } - } - - @Override - public ImplLifecycle getLifecycle() { - return mLifecycle; - } - - @Override - public void addSurface(Surface videoSurface) { - this.surface = videoSurface; - } - - @Override - public void addPlayerStatuCallback(StatuChangeListener callback) { - if (callback != null) { - statuChangeCallbacks.add(callback); - } - } - - @Override - public void removePlayerStatuCallback(StatuChangeListener callback) { - statuChangeCallbacks.remove(callback); - } - - @Override - public void addPlayerViewCallback(ScreenChangeListener callback) { - if (callback != null) { - screenChangeCallbacks.add(callback); - } - } - - @Override - public void removePlayerViewCallback(ScreenChangeListener callback) { - screenChangeCallbacks.remove(callback); - } - - @Override - public Builder getBuilder() { - return mBuilder; - } - - @Override - public PlayerStatu getPlayerStatu() { - return mStatu; - } - - @Override - public void resizeScreen(int width, int height) { - for (ScreenChangeListener screenChangeCallback : screenChangeCallbacks) { - screenChangeCallback.screenCallback(width, height); - } - } - - @Override - public void openGesture(boolean isOpen) { - isGestureOpen = isOpen; - } - - @Override - public boolean isGestureOpen() { - return isPlaying() && isGestureOpen; - } - - @Override - public void play() { - if (mPlayer != null) { - mPlayer.reset(); - } - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PREPARING; - callback.statuCallback(PlayerStatu.PREPARING); - } - initBasePlayer(); - start(); - } - - @Override - public void replay() { - if (isPlaying()) { - rewindTo(0); - } else { - reload(mBuilder.filePath, 0); - } - } - - @Override - public void reload(String filepath, int startMillisecond) { - mBuilder.filePath = filepath; - mBuilder.startMillisecond = startMillisecond; - play(); - } - - @Override - public void stop() { - if (mPlayer == null) { - return; - } - mPlayer.stop(); - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.STOP; - callback.statuCallback(PlayerStatu.STOP); - } - } - - @Override - public void release() { - if (mPlayer == null) { - return; - } - if (mStatu != PlayerStatu.IDEL) { - videoScale = Constants.NUMBER_NEGATIVE_1; - mPlayer.release(); - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.IDEL; - callback.statuCallback(PlayerStatu.IDEL); - } - } - } - - @Override - public void resume() { - if (mPlayer == null) { - return; - } - if (mStatu != PlayerStatu.IDEL) { - if (!isPlaying()) { - mPlayer.play(); - } - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PLAY; - callback.statuCallback(PlayerStatu.PLAY); - } - } - } - - @Override - public void pause() { - if (mPlayer == null) { - return; - } - if (isPlaying()) { - mPlayer.pause(); - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.PAUSE; - callback.statuCallback(PlayerStatu.PAUSE); - } - } - } - - @Override - public int getCurrentPosition() { - if (mPlayer == null) { - return 0; - } - return mPlayer.getCurrentTime(); - } - - @Override - public int getDuration() { - if (mPlayer == null) { - return 0; - } - return mPlayer.getDuration(); - } - - @Override - public float getVolume() { - return currentVolume; - } - - @Override - public void setVolume(float volume) { - if (mPlayer != null) { - if (mPlayer.setVolume(volume)) { - currentVolume = volume; - } - } - } - - @Override - public void setPlaySpeed(float speed) { - if (mPlayer == null) { - return; - } - if (mStatu != PlayerStatu.IDEL) { - mPlayer.setPlaybackSpeed(speed); - } - } - - @Override - public double getVideoScale() { - return videoScale; - } - - @Override - public boolean isPlaying() { - if (mPlayer != null) { - return mPlayer.isNowPlaying(); - } - return false; - } - - @Override - public void rewindTo(int startMicrosecond) { - if (mPlayer == null) { - return; - } - if (mStatu != PlayerStatu.IDEL) { - for (StatuChangeListener callback : statuChangeCallbacks) { - mStatu = PlayerStatu.BUFFERING; - callback.statuCallback(PlayerStatu.BUFFERING); - } - mPlayer.rewindTo(startMicrosecond * MICRO_MILLI_RATE); - } - } - - /** - * Builder - * - * @since 2020-12-04 - */ - public static class Builder { - private Context mContext; - private String filePath; - private int startMillisecond; - private boolean isStretch; - private boolean isPause; - - /** - * constructor of Builder - * - * @param context context - */ - public Builder(Context context) { - mContext = context; - filePath = ""; - startMillisecond = 0; - } - - /** - * setFilePath of Builder - * - * @param filePath filePath - * @return builder - */ - public Builder setFilePath(String filePath) { - this.filePath = filePath; - return this; - } - - /** - * getFilePath of Builder - * - * @return filePath - */ - public String getFilePath() { - return filePath; - } - - /** - * setStartMillisecond of Builder - * - * @param startMillisecond startMillisecond - * @return builder - */ - public Builder setStartMillisecond(int startMillisecond) { - this.startMillisecond = startMillisecond; - return this; - } - - /** - * getStartMillisecond of Builder - * - * @return startMillisecond - */ - public int getStartMillisecond() { - return startMillisecond; - } - - /** - * setStretch of Builder - * - * @param isS isStretch - * @return Builder - */ - public Builder setStretch(boolean isS) { - this.isStretch = isS; - return this; - } - - /** - * setPause of Builder - * - * @param isP isPause - * @return Builder - */ - public Builder setPause(boolean isP) { - this.isPause = isP; - return this; - } - - /** - * create of Builder - * - * @return IPlayer - */ - public ImplPlayer create() { - return new HmPlayer(this); - } - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java deleted file mode 100644 index b9229f4722633e21ba8fd61a8635be0e4a490178..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplLifecycle.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -/** - * ImplLifecycle - * - * @since 2021-04-09 - * - */ -public interface ImplLifecycle { - /** - * onStart - * - */ - void onStart(); - - /** - * onForeground - * - */ - void onForeground(); - - /** - * onBackground - * - */ - void onBackground(); - - /** - * onStop - * - */ - void onStop(); -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayModule.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayModule.java deleted file mode 100644 index f647ba9dedcf33df483d97d933cf277e26da1957..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayModule.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -/** - * IPlayModuler - * - * @since 2021-04-09 - * - */ -public interface ImplPlayModule { - /** - * bind - * - * @param player player - */ - void bind(ImplPlayer player); - - /** - * unbind - * - */ - void unbind(); -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java deleted file mode 100644 index 9ee31bc3e002bb02eda957da6ed7e27080da48c0..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ImplPlayer.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -import com.huawei.codelab.player.HmPlayer; -import com.huawei.codelab.player.constant.PlayerStatu; - -import ohos.agp.graphics.Surface; - -/** - * IPlayer interface - * - * @since 2021-04-04 - */ -public interface ImplPlayer { - /** - * addSurface - * - * @param surface surface - */ - void addSurface(Surface surface); - - /** - * addPlayerStatuCallback - * - * @param callback callback - */ - void addPlayerStatuCallback(StatuChangeListener callback); - - /** - * removePlayerStatuCallback - * - * @param callback callback - */ - void removePlayerStatuCallback(StatuChangeListener callback); - - /** - * addPlayerViewCallback - * - * @param callback callback - */ - void addPlayerViewCallback(ScreenChangeListener callback); - - /** - * removePlayerViewCallback - * - * @param callback callback - */ - void removePlayerViewCallback(ScreenChangeListener callback); - - /** - * play - */ - void play(); - - /** - * replay - */ - void replay(); - - /** - * reload - * - * @param filepath filepath - * @param startMillisecond startMillisecond - */ - void reload(String filepath, int startMillisecond); - - /** - * resume - */ - void resume(); - - /** - * pause - */ - void pause(); - - /** - * getCurrentPosition - * - * @return current position - */ - int getCurrentPosition(); - - /** - * getDuration - * - * @return duration - */ - int getDuration(); - - /** - * getVolume - * - * @return float - */ - float getVolume(); - - /** - * set play volume - * - * @param volume 0~1 - */ - void setVolume(float volume); - - /** - * set play speed - * - * @param speed 0~12 - */ - void setPlaySpeed(float speed); - - /** - * getVideoScale - * - * @return double - */ - double getVideoScale(); - - /** - * rewindTo - * - * @param startMicrosecond startMicrosecond(ms) - */ - void rewindTo(int startMicrosecond); - - /** - * isPlaying - * - * @return isPlaying - */ - boolean isPlaying(); - - /** - * stop - */ - void stop(); - - /** - * release - */ - void release(); - - /** - * getLifecycle - * - * @return ImplLifecycle - */ - ImplLifecycle getLifecycle(); - - /** - * getBuilder - * - * @return Builder - */ - HmPlayer.Builder getBuilder(); - - /** - * getPlayerStatu - * - * @return PlayerStatu - */ - PlayerStatu getPlayerStatu(); - - /** - * resizeScreen - * - * @param width width - * @param height height - */ - void resizeScreen(int width, int height); - - /** - * openGesture - * - * @param isOpen isOpen - */ - void openGesture(boolean isOpen); - - /** - * openGesture - * - * @return isGestureOpen - */ - boolean isGestureOpen(); -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java deleted file mode 100644 index 2081c98ce203bc8f35e6476ead5e2f082d0d2f26..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/ScreenChangeListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -/** - * ScreenChangeListener interface - * - * @since 2021-04-04 - * - */ -public interface ScreenChangeListener { - /** - * screenCallback - * - * @param width width - * @param height height - */ - void screenCallback(int width, int height); -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatuChangeListener.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatuChangeListener.java deleted file mode 100644 index 3032bf44d2999b395375ec43babb73887457f797..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/api/StatuChangeListener.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.api; - -import com.huawei.codelab.player.constant.PlayerStatu; - -/** - * StatuChangeListener interface - * - * @since 2021-04-04 - * - */ -public interface StatuChangeListener { - /** - * statuCallback - * - * @param statu statu - */ - void statuCallback(PlayerStatu statu); -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java deleted file mode 100644 index 2c581152b415b47db6caba2c214cb81dbe2c9962..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/Constants.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.constant; - -/** - * Constants - * - * @since 2021-04-04 - */ -public class Constants { - /** - * -1 - */ - public static final int NUMBER_NEGATIVE_1 = -1; - /** - * 2 - */ - public static final int NUMBER_2 = 2; - /** - * 2.0 - */ - public static final float NUMBER_FLOAT_2 = 2f; - /** - * 10 - */ - public static final int NUMBER_10 = 10; - /** - * 25 - */ - public static final int NUMBER_25 = 25; - /** - * 36 - */ - public static final int NUMBER_36 = 36; - /** - * 40 - */ - public static final int NUMBER_40 = 40; - /** - * 100 - */ - public static final int NUMBER_100 = 100; - /** - * 300 - */ - public static final int NUMBER_300 = 300; - /** - * 150 - */ - public static final int NUMBER_150 = 150; - /** - * 1000 - */ - public static final int NUMBER_1000 = 1000; - /** - * running - */ - public static final int PLAYER_PROGRESS_RUNNING = 0; - /** - * hide - */ - public static final int PLAYER_CONTROLLER_HIDE = 1; - /** - * hide - */ - public static final int PLAYER_CONTROLLER_SHOW = 2; - /** - * 100 - */ - public static final int ONE_HUNDRED_PERCENT = 100; - /** - * rewind step - */ - public static final int REWIND_STEP = 5000; - /** - * volume step - */ - public static final int VOLUME_STEP = 5; - /** - * INTENT STARTTIME PARAM - */ - public static final String INTENT_STARTTIME_PARAM = "intetn_starttime_param"; - /** - * INTENT PLAYURL PARAM - */ - public static final String INTENT_PLAYURL_PARAM = "intetn_playurl_param"; - /** - * INTENT PLAYSTATU PARAM - */ - public static final String INTENT_PLAYSTATU_PARAM = "intetn_playstatu_param"; - /** - * INTENT LANDSCREEN REQUEST CODE - */ - public static final int INTENT_LANDSCREEN_REQUEST_CODE = 1001; - - private Constants() { - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/GestureConst.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/GestureConst.java deleted file mode 100644 index d13417eba417a7dd30b2886f4e4e7fa370330469..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/GestureConst.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - */ - -package com.huawei.codelab.player.constant; - -/** - * GestureConst - * - * @since 2021-04-04 - */ -public class GestureConst { - private static final int DEFAULT_LONG_PRESS_TIMEOUT = 500; - - private static final int TOUCH_SLOP = 64; - - private static final int TAP_TIMEOUT = 100; - - private static final int DOUBLE_TAP_TIMEOUT = 300; - - private static final int DOUBLE_TAP_MIN_TIME = 40; - - private static final int DOUBLE_TAP_SLOP = 100; - - private static final int MINIMUM_FLING_VELOCITY = 50; - - private static final int MAXIMUM_FLING_VELOCITY = 8000; - - private static final int DOUBLE_TAP_TOUCH_SLOP = TOUCH_SLOP; - - private static final float AMBIGUOUS_GESTURE_MULTIPLIER = 2f; - - private GestureConst() { - } - - /** - * getDoubleTapTimeout - * - * @return int - */ - public static int getDoubleTapTimeout() { - return DOUBLE_TAP_TIMEOUT; - } - - /** - * getDoubleTapMinTime - * - * @return int - */ - public static int getDoubleTapMinTime() { - return DOUBLE_TAP_MIN_TIME; - } - - /** - * getTouchSlop - * - * @return int - */ - public static int getTouchSlop() { - return TOUCH_SLOP; - } - - /** - * getLongPressTimeout - * - * @return int - */ - public static int getLongPressTimeout() { - return DEFAULT_LONG_PRESS_TIMEOUT; - } - - /** - * getTapTimeout - * - * @return int - */ - public static int getTapTimeout() { - return TAP_TIMEOUT; - } - - /** - * getDoubleTapSlop - * - * @return int - */ - public static int getDoubleTapSlop() { - return DOUBLE_TAP_SLOP; - } - - /** - * getMinimumFlingVelocity - * - * @return int - */ - public static int getMinimumFlingVelocity() { - return MINIMUM_FLING_VELOCITY; - } - - /** - * getMaximumFlingVelocity - * - * @return int - */ - public static int getMaximumFlingVelocity() { - return MAXIMUM_FLING_VELOCITY; - } - - /** - * getScaledTouchSlop - * - * @return int - */ - public static int getScaledTouchSlop() { - return TOUCH_SLOP; - } - - /** - * getScaledDoubleTapTouchSlop - * - * @return int - */ - public static int getScaledDoubleTapTouchSlop() { - return DOUBLE_TAP_TOUCH_SLOP; - } - - /** - * getScaledDoubleTapSlop - * - * @return int - */ - public static int getScaledDoubleTapSlop() { - return DOUBLE_TAP_SLOP; - } - - /** - * getScaledMinimumFlingVelocity - * - * @return int - */ - public static int getScaledMinimumFlingVelocity() { - return MINIMUM_FLING_VELOCITY; - } - - /** - * getScaledMaximumFlingVelocity - * - * @return int - */ - public static int getScaledMaximumFlingVelocity() { - return MAXIMUM_FLING_VELOCITY; - } - - /** - * getAmbiguousGestureMultiplier - * - * @return int - */ - public static float getAmbiguousGestureMultiplier() { - return AMBIGUOUS_GESTURE_MULTIPLIER; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatu.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatu.java deleted file mode 100644 index 8c43c509012fd0f0a84611436dee8e4eb3c785d0..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/constant/PlayerStatu.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.constant; - -/** - * PlayerStatu enum - * - * @since 2021-04-04 - * - */ -public enum PlayerStatu { - /** - * idel - * - */ - IDEL, - /** - * preparing - * - */ - PREPARING, - /** - * prepared - * - */ - PREPARED, - /** - * play - * - */ - PLAY, - /** - * pause - * - */ - PAUSE, - /** - * stop - * - */ - STOP, - /** - * complete - * - */ - COMPLETE, - /** - * error - * - */ - ERROR, - /** - * buffering - * - */ - BUFFERING -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java deleted file mode 100644 index e186decf1ae892642b790f4d3702f1f75dd04b25..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/factory/SourceFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.factory; - -import com.huawei.codelab.util.LogUtil; - -import ohos.app.Context; -import ohos.global.resource.RawFileDescriptor; -import ohos.media.common.Source; - -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.IOException; - -/** - * SourceFactory - * - * @since 2021-04-04 - * - */ -public class SourceFactory { - private static final String TAG = "SourceFactory"; - private static final String NET_HTTP_MATCH = "http"; - private static final String NET_RTMP_MATCH = "rtmp"; - private static final String NET_RTSP_MATCH = "rtsp"; - private static final String STORAGE_MATCH = "/storage/"; - - private Source mPlayerSource; - - /** - * constructor of SourceFactory - * - * @param context context - * @param path path - */ - public SourceFactory(Context context, String path) { - try { - initSourceType(context, path); - } catch (IOException e) { - LogUtil.error(TAG, "Audio resource is unavailable: "); - } - } - - private void initSourceType(Context context, String path) throws IOException { - if (context == null || path == null) { - return; - } - if (path.substring(0, NET_HTTP_MATCH.length()).equalsIgnoreCase(NET_HTTP_MATCH) - || path.substring(0, NET_RTMP_MATCH.length()).equalsIgnoreCase(NET_RTMP_MATCH) - || path.substring(0, NET_RTSP_MATCH.length()).equalsIgnoreCase(NET_RTSP_MATCH)) { - mPlayerSource = new Source(path); - } else if (path.startsWith(STORAGE_MATCH)) { - File file = new File(path); - if (file.exists()) { - FileInputStream fileInputStream = new FileInputStream(file); - FileDescriptor fileDescriptor = fileInputStream.getFD(); - mPlayerSource = new Source(fileDescriptor); - } - } else { - RawFileDescriptor fd = context.getResourceManager().getRawFileEntry(path).openRawFileDescriptor(); - mPlayerSource = new Source(fd.getFileDescriptor(), fd.getStartPosition(), fd.getFileSize()); - } - } - - /** - * getSource - * - * @return Source Source - */ - public Source getSource() { - return mPlayerSource; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/GestureDetector.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/GestureDetector.java deleted file mode 100644 index d5c19e9c1a3fd924c14cad6dcd0394bf48a531ee..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/GestureDetector.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - */ - -package com.huawei.codelab.player.manager; - -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.GestureConst; - -import ohos.agp.components.VelocityDetector; -import ohos.multimodalinput.event.TouchEvent; - -/** - * GestureDetector - * - * @since 2021-04-09 - */ -public class GestureDetector { - /** - * MOVING_HORIZONTAL - */ - public static final int MOVING_HORIZONTAL = 0; - /** - * MOVING_VERTICAL - */ - public static final int MOVING_VERTICAL = 1; - private int currentMoveType; - - /** - * OnGestureListener - * - * @since 2021-04-09 - */ - public interface OnGestureListener { - /** - * 开始滚动时回调 - * - * @param windowX 手指移动时x位置 - * @param windowY 手指移动时y位置 - * @return is deliver - */ - boolean onTouchBegin(float windowX, float windowY); - - /** - * 发生滚动时回调 - * - * @param direction 移动方向 0:横向 1:纵向 - * @param windowX 手指移动时x位置 - * @param windowY 手指移动时y位置 - * @param distance 移动距离 - * @return is deliver - */ - boolean onTouchMoving(int direction, float windowX, float windowY, float distance); - - /** - * 结束滚动时回调 - * - * @param direction 移动方向 0:横向 1:纵向 - * @return is deliver - */ - boolean onTouchCancel(int direction); - } - - private final OnGestureListener mListener; - - private float mLastFocusX; - private float mLastFocusY; - private float mDownFocusX; - private float mDownFocusY; - - private VelocityDetector mVelocityTracker; - - /** - * GestureDetector - * - * @param listener listener - */ - public GestureDetector(OnGestureListener listener) { - mListener = listener; - } - - /** - * onTouchEvent - * - * @param ev ev - * @return boolean - */ - public boolean onTouchEvent(TouchEvent ev) { - final int action = ev.getAction(); - addVelocityDetector(ev); - float[] points = getFocusPoint(ev); - final float focusX = points[0]; - final float focusY = points[1]; - boolean isHandled = true; - switch (action) { - case TouchEvent.OTHER_POINT_DOWN: - case TouchEvent.PRIMARY_POINT_DOWN: - currentMoveType = Constants.NUMBER_NEGATIVE_1; - mDownFocusX = 0; - mDownFocusY = 0; - mListener.onTouchBegin(focusX, focusY); - break; - case TouchEvent.POINT_MOVE: - if (mDownFocusX == 0 || mDownFocusY == 0) { - mDownFocusX = focusX; - mDownFocusY = focusY; - mLastFocusX = focusX; - mLastFocusY = focusY; - } - final int deltaX = (int) (focusX - mDownFocusX); - final int deltaY = (int) (focusY - mDownFocusY); - int distanceX = Math.abs(deltaX); - int distanceY = Math.abs(deltaY); - if (distanceX > GestureConst.getScaledTouchSlop() || distanceY > GestureConst.getScaledTouchSlop()) { - if (distanceX >= distanceY) { - currentMoveType = MOVING_HORIZONTAL; - float scrollX = mLastFocusX - focusX; - isHandled = mListener.onTouchMoving(MOVING_HORIZONTAL, focusX, focusY, scrollX); - } else { - currentMoveType = MOVING_VERTICAL; - float scrollY = mLastFocusY - focusY; - isHandled = mListener.onTouchMoving(MOVING_VERTICAL, focusX, focusY, scrollY); - } - mLastFocusX = focusX; - mLastFocusY = focusY; - } - break; - case TouchEvent.PRIMARY_POINT_UP: - case TouchEvent.OTHER_POINT_UP: - case TouchEvent.CANCEL: - isHandled = mListener.onTouchCancel(currentMoveType); - break; - default: - break; - } - return isHandled; - } - - private void addVelocityDetector(TouchEvent ev) { - if (mVelocityTracker == null) { - mVelocityTracker = VelocityDetector.obtainInstance(); - } - mVelocityTracker.addEvent(ev); - } - - private float[] getFocusPoint(TouchEvent ev) { - final boolean isPointerUp = ev.getAction() == TouchEvent.OTHER_POINT_UP; - final int skipIndex = isPointerUp ? ev.getIndex() : Constants.NUMBER_NEGATIVE_1; - float sumX = 0; - float sumY = 0; - final int count = ev.getPointerCount(); - for (int i = 0; i < count; i++) { - if (skipIndex == i) { - continue; - } - sumX += ev.getPointerPosition(i).getX(); - sumY += ev.getPointerPosition(i).getY(); - } - final int div = isPointerUp ? count - 1 : count; - float focusX = sumX / div; - float focusY = sumY / div; - return new float[]{focusX, focusY}; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java deleted file mode 100644 index 8ed81c05d40c58fb0f49a77b6aae4c9a3aba83d9..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/manager/HmPlayerLifecycle.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.manager; - -import com.huawei.codelab.player.api.ImplLifecycle; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.PlayerStatu; - -/** - * HmPlayerLifecycle - * - * @since 2021-04-09 - * - */ -public class HmPlayerLifecycle implements ImplLifecycle { - private static final String TAG = HmPlayerLifecycle.class.getSimpleName(); - private ImplPlayer mPlayer; - - /** - * HmPlayerLifecycle - * - * @param player player - */ - public HmPlayerLifecycle(ImplPlayer player) { - mPlayer = player; - } - - @Override - public void onStart() { - } - - @Override - public void onForeground() { - String url = mPlayer.getBuilder().getFilePath(); - int startMillisecond = mPlayer.getBuilder().getStartMillisecond(); - mPlayer.reload(url, startMillisecond); - } - - @Override - public void onBackground() { - mPlayer.getBuilder().setPause(mPlayer.getPlayerStatu() == PlayerStatu.PAUSE); - mPlayer.getBuilder().setStartMillisecond(mPlayer.getCurrentPosition()); - mPlayer.release(); - } - - @Override - public void onStop() { - mPlayer.release(); - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/CommonUtils.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/CommonUtils.java deleted file mode 100644 index e3f589af90cf2639f5b12a45d7a80c9ec77ef300..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/CommonUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.util; - -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.util.LogUtil; - -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.global.resource.WrongTypeException; - -import java.io.IOException; - -/** - * Common util - * - * @since 2021-04-04 - */ -public class CommonUtils { - private static final String TAG = CommonUtils.class.getSimpleName(); - - private CommonUtils() { - } - - /** - * 通过资源ID获取颜色 - * - * @param context comtext - * @param resourceId id - * @return int - */ - public static int getColor(Context context, int resourceId) { - try { - return context.getResourceManager().getElement(resourceId).getColor(); - } catch (IOException | NotExistException | WrongTypeException e) { - LogUtil.error(TAG, e.getMessage()); - } - return Constants.NUMBER_NEGATIVE_1; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/DateUtils.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/DateUtils.java deleted file mode 100644 index 8b83ee326f3312f9bfd0af98cb77ee22306bdeb7..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/util/DateUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.util; - -import java.util.Locale; - -/** - * Date util - * - * @since 2021-04-04 - */ -public class DateUtils { - private static final int ONE_SECONDS_MS = 1000; - private static final int ONE_MINS_MINUTES = 60; - private static final int NUMBER = 16; - private static final String TIME_FORMAT = "%02d"; - private static final String SEMICOLON = ":"; - - private DateUtils() { - } - - /** - * conversion of msToString - * - * @param ms ms - * @return string - */ - public static String msToString(int ms) { - StringBuilder sb = new StringBuilder(NUMBER); - int seconds = ms / ONE_SECONDS_MS; - int minutes = seconds / ONE_MINS_MINUTES; - if (minutes > ONE_MINS_MINUTES) { - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes / ONE_MINS_MINUTES)); - sb.append(SEMICOLON); - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes % ONE_MINS_MINUTES)); - sb.append(SEMICOLON); - } else { - sb.append("00:"); - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes)); - sb.append(SEMICOLON); - } - - if (seconds > minutes * ONE_MINS_MINUTES) { - sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, seconds - minutes * ONE_MINS_MINUTES)); - } else { - sb.append("00"); - } - return sb.toString(); - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerGestureView.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerGestureView.java deleted file mode 100644 index af65e967b7de868dc01ee8467794ad5902934036..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerGestureView.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - */ - -package com.huawei.codelab.player.view; - -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.player.api.ImplPlayModule; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.PlayerStatu; -import com.huawei.codelab.player.manager.GestureDetector; -import com.huawei.codelab.player.util.CommonUtils; -import com.huawei.codelab.player.util.DateUtils; - -import ohos.agp.colors.RgbColor; -import ohos.agp.components.AttrSet; -import ohos.agp.components.DirectionalLayout; -import ohos.agp.components.Image; -import ohos.agp.components.Text; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.utils.Color; -import ohos.agp.utils.LayoutAlignment; -import ohos.app.Context; - -/** - * PlayerGestureView - * - * @since 2021-04-04 - */ -public class PlayerGestureView extends DirectionalLayout implements ImplPlayModule, GestureDetector.OnGestureListener { - private static final int MOVING_TYPE_INIT = -1; - private static final int VOLUME_TYPE = 0; - private static final int PROGRESS_DOWN_TYPE = 1; - private static final int PROGRESS_UP_TYPE = 2; - private static final int LIGHT_BRIGHT_TYPE = 3; - private ImplPlayer player; - private int currentPercent; - private int currentMoveType; - private int beginPosition; - - private Image gestureImage; - private Text gestureText; - - /** - * constructor of PlayerGestureView - * - * @param context context - */ - public PlayerGestureView(Context context) { - this(context, null); - } - - /** - * constructor of PlayerGestureView - * - * @param context context - * @param attrSet attSet - */ - public PlayerGestureView(Context context, AttrSet attrSet) { - this(context, attrSet, null); - } - - /** - * constructor of PlayerGestureView - * - * @param context context - * @param attrSet attSet - * @param styleName styleName - */ - public PlayerGestureView(Context context, AttrSet attrSet, String styleName) { - super(context, attrSet, styleName); - initView(); - hide(); - } - - private void initView() { - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor( - RgbColor.fromArgbInt(CommonUtils.getColor(mContext, ResourceTable.Color_half_transparent))); - shapeElement.setCornerRadius(Constants.NUMBER_25); - setOrientation(DirectionalLayout.VERTICAL); - setAlignment(LayoutAlignment.HORIZONTAL_CENTER); - setBackground(shapeElement); - gestureImage = new Image(mContext); - gestureImage.setWidth(Constants.NUMBER_150); - gestureImage.setHeight(Constants.NUMBER_150); - gestureImage.setScaleMode(Image.ScaleMode.STRETCH); - gestureImage.setMarginsTopAndBottom(Constants.NUMBER_40, Constants.NUMBER_10); - gestureText = new Text(mContext); - gestureText.setTextSize(Constants.NUMBER_36); - gestureText.setTextColor(new Color(CommonUtils.getColor(mContext, ResourceTable.Color_white))); - gestureText.setMarginsTopAndBottom(Constants.NUMBER_10, Constants.NUMBER_40); - addComponent(gestureImage); - addComponent(gestureText); - } - - private void show(int type, String content) { - int gestureImg = ResourceTable.Media_ic_horns; - switch (type) { - case VOLUME_TYPE: - gestureImg = ResourceTable.Media_ic_horns; - break; - case PROGRESS_DOWN_TYPE: - gestureImg = ResourceTable.Media_ic_backward; - break; - case PROGRESS_UP_TYPE: - gestureImg = ResourceTable.Media_ic_forward; - break; - case LIGHT_BRIGHT_TYPE: - gestureImg = ResourceTable.Media_ic_bright; - break; - default: - break; - } - gestureImage.setPixelMap(gestureImg); - gestureText.setText(content); - if (getVisibility() != VISIBLE) { - setVisibility(VISIBLE); - } - } - - private void hide() { - if (getVisibility() == VISIBLE) { - setVisibility(HIDE); - } - } - - @Override - public void bind(ImplPlayer implPlayer) { - this.player = implPlayer; - this.player.addPlayerStatuCallback(statu -> { - mContext.getUITaskDispatcher().asyncDispatch(() -> { - if (statu == PlayerStatu.STOP || statu == PlayerStatu.COMPLETE) { - hide(); - } - }); - }); - } - - @Override - public void unbind() { - } - - @Override - public boolean onTouchBegin(float focusX, float focusY) { - if (player != null) { - currentPercent = 0; - currentMoveType = MOVING_TYPE_INIT; - beginPosition = player.getCurrentPosition(); - } - return true; - } - - @Override - public boolean onTouchMoving(int direction, float focusX, float focusY, float distance) { - if (currentMoveType == MOVING_TYPE_INIT) { - currentMoveType = direction; - } - if (currentMoveType == direction && player != null) { - if (currentMoveType == GestureDetector.MOVING_HORIZONTAL) { - currentPercent += distance < 0 ? Constants.NUMBER_1000 : -Constants.NUMBER_1000; - int type = currentPercent < 0 - ? PlayerGestureView.PROGRESS_DOWN_TYPE : PlayerGestureView.PROGRESS_UP_TYPE; - int value = Math.abs(currentPercent); - String content = (currentPercent < 0 ? "- " : "+ ") + DateUtils.msToString(value); - show(type, content); - } else if (currentMoveType == GestureDetector.MOVING_VERTICAL) { - int interval = getHeight() / Constants.NUMBER_2; - if (focusX <= getWidth() / Constants.NUMBER_FLOAT_2) { - show(PlayerGestureView.LIGHT_BRIGHT_TYPE, "100%"); - } else { - float volume = player.getVolume() + distance / interval; - volume = (volume < 0) ? 0 : Math.min(volume, 1); - show(PlayerGestureView.VOLUME_TYPE, (int) (volume * Constants.NUMBER_100) + "%"); - player.setVolume(volume); - } - } else { - return false; - } - } - return true; - } - - @Override - public boolean onTouchCancel(int direction) { - if (currentMoveType == GestureDetector.MOVING_HORIZONTAL && player != null) { - player.rewindTo(beginPosition + currentPercent); - } - hide(); - return true; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerLoading.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerLoading.java deleted file mode 100644 index 18238ada4556dce307d9abb2ae16e5b67a478a7d..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerLoading.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.view; - -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.player.api.ImplPlayModule; -import com.huawei.codelab.player.api.ImplPlayer; - -import ohos.agp.animation.AnimatorProperty; -import ohos.agp.components.AttrSet; -import ohos.agp.components.Component; -import ohos.agp.components.Component.TouchEventListener; -import ohos.agp.components.ComponentContainer; -import ohos.agp.components.Image; -import ohos.agp.components.LayoutScatter; -import ohos.app.Context; -import ohos.multimodalinput.event.TouchEvent; - -/** - * PlayerLoading - * - * @since 2021-04-04 - */ -public class PlayerLoading extends ComponentContainer implements ImplPlayModule, TouchEventListener { - private static final int HALF_NUMBER = 2; - private static final int ANIM_ROTATE = 360; - private static final int ANIM_DURATION = 2000; - private static final int ANIM_LOOPED_COUNT = -1; - private ImplPlayer mPlayer; - private Image mLoading; - private AnimatorProperty mLoadingAnim; - - /** - * constructor of PlayerLoading - * - * @param context context - */ - public PlayerLoading(Context context) { - this(context, null); - } - - /** - * constructor of PlayerLoading - * - * @param context context - * @param attrSet attSet - */ - public PlayerLoading(Context context, AttrSet attrSet) { - this(context, attrSet, null); - } - - /** - * constructor of PlayerLoading - * - * @param context context - * @param attrSet attSet - * @param styleName styleName - */ - public PlayerLoading(Context context, AttrSet attrSet, String styleName) { - super(context, attrSet, styleName); - initView(context); - } - - private void initView(Context context) { - Component loadingContainer = - LayoutScatter.getInstance(context).parse(ResourceTable.Layout_player_loading_layout, null, false); - if (loadingContainer.findComponentById(ResourceTable.Id_image_loading) instanceof Image) { - mLoading = (Image) loadingContainer.findComponentById(ResourceTable.Id_image_loading); - initAnim(); - } - addComponent(loadingContainer); - hide(); - setTouchEventListener(this); - } - - private void initAnim() { - int with = mLoading.getWidth() / HALF_NUMBER; - int height = mLoading.getHeight() / HALF_NUMBER; - mLoading.setPivotX(with); - mLoading.setPivotY(height); - mLoadingAnim = mLoading.createAnimatorProperty(); - mLoadingAnim.rotate(ANIM_ROTATE).setDuration(ANIM_DURATION).setLoopedCount(ANIM_LOOPED_COUNT); - } - - private void initListener() { - mPlayer.addPlayerStatuCallback(statu -> mContext.getUITaskDispatcher().asyncDispatch(() -> { - switch (statu) { - case PREPARING: - case BUFFERING: - show(); - break; - case PLAY: - hide(); - break; - default: - break; - } - })); - } - - /** - * show of PlayerLoading - */ - public void show() { - if (mLoadingAnim.isPaused()) { - mLoadingAnim.resume(); - } else { - mLoadingAnim.start(); - } - setVisibility(VISIBLE); - } - - /** - * hide of PlayerLoading - */ - public void hide() { - setVisibility(INVISIBLE); - mLoadingAnim.pause(); - } - - @Override - public void bind(ImplPlayer player) { - mPlayer = player; - initListener(); - } - - @Override - public void unbind() { - mLoadingAnim.release(); - } - - @Override - public boolean onTouchEvent(Component component, TouchEvent touchEvent) { - return true; - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerView.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerView.java deleted file mode 100644 index f5cf9c774692b4195b7c7b7de4ad2d03a669f79c..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/PlayerView.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - */ - -package com.huawei.codelab.player.view; - -import com.huawei.codelab.player.api.ImplPlayModule; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.manager.GestureDetector; - -import ohos.agp.components.Attr; -import ohos.agp.components.AttrSet; -import ohos.agp.components.Component; -import ohos.agp.components.Component.LayoutRefreshedListener; -import ohos.agp.components.ComponentContainer; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.surfaceprovider.SurfaceProvider; -import ohos.agp.graphics.Surface; -import ohos.agp.graphics.SurfaceOps; -import ohos.agp.window.service.WindowManager; -import ohos.app.Context; - -import java.util.Optional; - -/** - * PlayerView - * - * @since 2021-04-04 - */ -public class PlayerView extends DependentLayout implements ImplPlayModule, LayoutRefreshedListener { - private ImplPlayer player; - private SurfaceProvider surfaceView; - private Surface surface; - private PlayerGestureView gestureView; - private GestureDetector gestureDetector; - private boolean isTopPlay; - private int viewWidth; - private int viewHeight; - - /** - * constructor of PlayerView - * - * @param context context - */ - public PlayerView(Context context) { - this(context, null); - } - - /** - * constructor of PlayerView - * - * @param context context - * @param attrSet attSet - */ - public PlayerView(Context context, AttrSet attrSet) { - this(context, attrSet, null); - } - - /** - * constructor of PlayerView - * - * @param context context - * @param attrSet attSet - * @param styleName styleName - */ - public PlayerView(Context context, AttrSet attrSet, String styleName) { - super(context, attrSet, styleName); - WindowManager.getInstance().getTopWindow().get().setTransparent(true); // 不设置窗体透明会挡住播放内容,除非设置pinToZTop为true - if (attrSet != null) { - Optional optIsTopPlay = attrSet.getAttr("top_play"); - optIsTopPlay.ifPresent(attr -> isTopPlay = "true".equals(attr.getStringValue())); - } - initView(); - initListener(); - setLayoutRefreshedListener(this); - } - - private void initView() { - surfaceView = new SurfaceProvider(mContext); - DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig(); - layoutConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); - surfaceView.setLayoutConfig(layoutConfig); - surfaceView.pinToZTop(isTopPlay); - addComponent(surfaceView); - addGestureView(); - } - - private void addGestureView() { - gestureView = new PlayerGestureView(mContext); - DependentLayout.LayoutConfig config = - new DependentLayout.LayoutConfig(Constants.NUMBER_300, ComponentContainer.LayoutConfig.MATCH_CONTENT); - config.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); - gestureView.setLayoutConfig(config); - addComponent(gestureView); - } - - private void initListener() { - gestureDetector = new GestureDetector(gestureView); - surfaceView.setTouchEventListener((component, touchEvent) -> - canGesture() && gestureDetector.onTouchEvent(touchEvent)); - surfaceView.getSurfaceOps().ifPresent(surfaceOps -> surfaceOps.addCallback(new SurfaceOps.Callback() { - @Override - public void surfaceCreated(SurfaceOps surfaceOps) { - surface = surfaceOps.getSurface(); - if (player != null) { - player.addSurface(surface); - } - } - - @Override - public void surfaceChanged(SurfaceOps surfaceOps, int info, int width, int height) { - } - - @Override - public void surfaceDestroyed(SurfaceOps surfaceOps) { - } - })); - } - - private boolean canGesture() { - return gestureDetector != null - && player != null - && player.isGestureOpen(); - } - - private void updateVideoSize(double videoScale) { - if (videoScale > 1) { - surfaceView.setWidth(viewWidth); - surfaceView.setHeight((int) Math.min(viewWidth / videoScale, viewHeight)); - } else { - surfaceView.setHeight(viewHeight); - surfaceView.setWidth((int) Math.min(viewHeight * videoScale, viewWidth)); - } - } - - @Override - public void bind(ImplPlayer implPlayer) { - this.player = implPlayer; - gestureView.bind(player); - this.player.addPlayerViewCallback((width, height) -> mContext.getUITaskDispatcher().asyncDispatch(() -> { - if (width > 0) { - setWidth(width); - } - if (height > 0) { - setHeight(height); - } - })); - } - - @Override - public void unbind() { - surfaceView.removeFromWindow(); - surfaceView = null; - surface = null; - } - - @Override - public void onRefreshed(Component component) { - int newWidth = component.getWidth(); - int newHeight = component.getHeight(); - double videoScale = player.getVideoScale(); - if (videoScale != Constants.NUMBER_NEGATIVE_1 && (newWidth != viewWidth || newHeight != viewHeight)) { - viewWidth = newWidth; - viewHeight = newHeight; - mContext.getUITaskDispatcher().asyncDispatch(() -> updateVideoSize(videoScale)); - } - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/SimplePlayerController.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/SimplePlayerController.java deleted file mode 100644 index 421e9c654819b59ae82410b3130b32f0ff2a3c60..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/player/view/SimplePlayerController.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.player.view; - -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.player.api.ImplPlayModule; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.api.StatuChangeListener; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.constant.PlayerStatu; -import com.huawei.codelab.player.util.DateUtils; - -import ohos.agp.colors.RgbColor; -import ohos.agp.components.AttrSet; -import ohos.agp.components.Component; -import ohos.agp.components.ComponentContainer; -import ohos.agp.components.DependentLayout; -import ohos.agp.components.DirectionalLayout; -import ohos.agp.components.Image; -import ohos.agp.components.LayoutScatter; -import ohos.agp.components.Slider; -import ohos.agp.components.Text; -import ohos.agp.components.element.ShapeElement; -import ohos.app.Context; -import ohos.eventhandler.EventHandler; -import ohos.eventhandler.EventRunner; -import ohos.eventhandler.InnerEvent; - -/** - * PlayerController - * - * @since 2021-04-04 - */ -public class SimplePlayerController extends ComponentContainer implements ImplPlayModule { - private static final int THUMB_RED = 255; - private static final int THUMB_GREEN = 255; - private static final int THUMB_BLUE = 240; - private static final int THUMB_WIDTH = 40; - private static final int THUMB_HEIGHT = 40; - private static final int THUMB_RADIUS = 20; - private static final int CONTROLLER_HIDE_DLEY_TIME = 5000; - private static final int PROGRESS_RUNNING_TIME = 1000; - private boolean mIsDragMode = false; - private Context mContext; - private ImplPlayer mPlayer; - private DependentLayout topLayout; - private DirectionalLayout bottomLayout; - private Image mBack; - private Image mPlayToogle; - private Image mForward; - private Image mBackward; - private Slider mProgressBar; - private Text mCurrentTime; - private Text mTotleTime; - private ControllerHandler mHandler; - private StatuChangeListener mStatuChangeListener = new StatuChangeListener() { - @Override - public void statuCallback(PlayerStatu statu) { - mContext.getUITaskDispatcher().asyncDispatch(() -> { - switch (statu) { - case PREPARING: - mPlayToogle.setClickable(false); - mProgressBar.setEnabled(false); - mProgressBar.setProgressValue(0); - break; - case PREPARED: - mProgressBar.setMaxValue(mPlayer.getDuration()); - mTotleTime.setText(DateUtils.msToString(mPlayer.getDuration())); - break; - case PLAY: - showController(false); - mPlayToogle.setPixelMap(ResourceTable.Media_ic_music_stop); - mPlayToogle.setClickable(true); - mProgressBar.setEnabled(true); - break; - case PAUSE: - mPlayToogle.setPixelMap(ResourceTable.Media_ic_music_play); - break; - case STOP: - case COMPLETE: - mPlayToogle.setPixelMap(ResourceTable.Media_ic_update); - mProgressBar.setEnabled(false); - break; - default: - break; - } - }); - } - }; - - /** - * constructor of SimplePlayerController - * - * @param context context - */ - public SimplePlayerController(Context context) { - this(context, null); - } - - /** - * constructor of SimplePlayerController - * - * @param context context - * @param attrSet attSet - */ - public SimplePlayerController(Context context, AttrSet attrSet) { - this(context, attrSet, null); - } - - /** - * constructor of SimplePlayerController - * - * @param context context - * @param attrSet attSet - * @param styleName styleName - */ - public SimplePlayerController(Context context, AttrSet attrSet, String styleName) { - super(context, attrSet, styleName); - mContext = context; - createHandler(); - initView(); - initListener(); - } - - private void createHandler() { - EventRunner runner = EventRunner.create(true); - if (runner == null) { - return; - } - mHandler = new ControllerHandler(runner); - } - - private void initView() { - Component playerController = - LayoutScatter.getInstance(mContext) - .parse(ResourceTable.Layout_simple_player_controller_layout, null, false); - addComponent(playerController); - if (playerController.findComponentById(ResourceTable.Id_controller_top_layout) instanceof DependentLayout) { - topLayout = (DependentLayout) playerController.findComponentById(ResourceTable.Id_controller_top_layout); - } - if (playerController.findComponentById(ResourceTable.Id_controller_bottom_layout) - instanceof DirectionalLayout) { - bottomLayout = (DirectionalLayout) playerController - .findComponentById(ResourceTable.Id_controller_bottom_layout); - } - if (playerController.findComponentById(ResourceTable.Id_back) instanceof Image) { - mBack = (Image) playerController.findComponentById(ResourceTable.Id_back); - } - if (playerController.findComponentById(ResourceTable.Id_play_controller) instanceof Image) { - mPlayToogle = (Image) playerController.findComponentById(ResourceTable.Id_play_controller); - } - if (playerController.findComponentById(ResourceTable.Id_play_forward) instanceof Image) { - mForward = (Image) playerController.findComponentById(ResourceTable.Id_play_forward); - } - if (playerController.findComponentById(ResourceTable.Id_play_backward) instanceof Image) { - mBackward = (Image) playerController.findComponentById(ResourceTable.Id_play_backward); - } - if (playerController.findComponentById(ResourceTable.Id_progress) instanceof Slider) { - mProgressBar = (Slider) playerController.findComponentById(ResourceTable.Id_progress); - } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(THUMB_RED, THUMB_GREEN, THUMB_BLUE)); - shapeElement.setBounds(0, 0, THUMB_WIDTH, THUMB_HEIGHT); - shapeElement.setCornerRadius(THUMB_RADIUS); - mProgressBar.setThumbElement(shapeElement); - if (playerController.findComponentById(ResourceTable.Id_current_time) instanceof Text) { - mCurrentTime = (Text) playerController.findComponentById(ResourceTable.Id_current_time); - } - if (playerController.findComponentById(ResourceTable.Id_end_time) instanceof Text) { - mTotleTime = (Text) playerController.findComponentById(ResourceTable.Id_end_time); - } - } - - private void initListener() { - topLayout.setTouchEventListener((component, touchEvent) -> true); - bottomLayout.setTouchEventListener((component, touchEvent) -> true); - mBack.setClickedListener(component -> mContext.terminateAbility()); - } - - private void initPlayListener() { - mPlayer.addPlayerStatuCallback(mStatuChangeListener); - mPlayToogle.setClickedListener(component -> { - if (mPlayer.isPlaying()) { - mPlayer.pause(); - } else { - if (mPlayer.getPlayerStatu() == PlayerStatu.STOP) { - mPlayer.replay(); - } else { - mPlayer.resume(); - } - } - }); - mForward.setClickedListener(component -> - mPlayer.rewindTo(mPlayer.getCurrentPosition() + Constants.REWIND_STEP)); - mBackward.setClickedListener(component -> - mPlayer.rewindTo(mPlayer.getCurrentPosition() - Constants.REWIND_STEP)); - mProgressBar.setValueChangedListener( - new Slider.ValueChangedListener() { - @Override - public void onProgressUpdated(Slider slider, int value, boolean isB) { - mContext.getUITaskDispatcher().asyncDispatch(() -> - mCurrentTime.setText(DateUtils.msToString(value))); - } - - @Override - public void onTouchStart(Slider slider) { - mIsDragMode = true; - mHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING, EventHandler.Priority.IMMEDIATE); - } - - @Override - public void onTouchEnd(Slider slider) { - mIsDragMode = false; - if (slider.getProgress() == mPlayer.getDuration()) { - mPlayer.stop(); - } else { - mPlayer.rewindTo(slider.getProgress()); - } - } - }); - } - - /** - * showController of PlayerController - * - * @param isAutoHide isAutoHide - */ - public void showController(boolean isAutoHide) { - mHandler.sendEvent(Constants.PLAYER_CONTROLLER_SHOW, EventHandler.Priority.HIGH); - if (isAutoHide) { - hideController(CONTROLLER_HIDE_DLEY_TIME); - } else { - mHandler.removeEvent(Constants.PLAYER_CONTROLLER_HIDE); - } - } - - /** - * hideController of PlayerController - * - * @param delay delay - */ - public void hideController(int delay) { - mHandler.removeEvent(Constants.PLAYER_CONTROLLER_HIDE); - mHandler.sendEvent(Constants.PLAYER_CONTROLLER_HIDE, delay, EventHandler.Priority.HIGH); - } - - @Override - public void bind(ImplPlayer player) { - mPlayer = player; - initPlayListener(); - } - - @Override - public void unbind() { - mHandler.removeAllEvent(); - mHandler = null; - } - - /** - * ControllerHandler - * - * @author chenweiquan - * @since 2020-12-04 - */ - private class ControllerHandler extends EventHandler { - private ControllerHandler(EventRunner runner) { - super(runner); - } - - @Override - public void processEvent(InnerEvent event) { - super.processEvent(event); - if (event == null) { - return; - } - switch (event.eventId) { - case Constants.PLAYER_PROGRESS_RUNNING: - if (mPlayer != null && mPlayer.isPlaying() && !mIsDragMode) { - mContext.getUITaskDispatcher().asyncDispatch(() -> { - mProgressBar.setProgressValue(mPlayer.getCurrentPosition()); - mCurrentTime.setText(DateUtils.msToString(mPlayer.getCurrentPosition())); - }); - mHandler.sendEvent( - Constants.PLAYER_PROGRESS_RUNNING, PROGRESS_RUNNING_TIME, Priority.IMMEDIATE); - } - break; - case Constants.PLAYER_CONTROLLER_HIDE: - mContext.getUITaskDispatcher().asyncDispatch(() -> setVisibility(INVISIBLE)); - mHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING); - break; - case Constants.PLAYER_CONTROLLER_SHOW: - mHandler.removeEvent(Constants.PLAYER_PROGRESS_RUNNING); - mHandler.sendEvent(Constants.PLAYER_PROGRESS_RUNNING, Priority.IMMEDIATE); - mContext.getUITaskDispatcher().asyncDispatch(() -> { - if (getVisibility() != VISIBLE) { - setVisibility(VISIBLE); - } - }); - break; - default: - break; - } - } - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java deleted file mode 100644 index 9002397fe2cb161100db30ea0ec3d8f36b2395b4..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/slice/SimplePlayerAbilitySlice.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.slice; - -import com.huawei.codelab.ResourceTable; -import com.huawei.codelab.player.HmPlayer; -import com.huawei.codelab.player.api.ImplPlayer; -import com.huawei.codelab.player.constant.Constants; -import com.huawei.codelab.player.view.PlayerLoading; -import com.huawei.codelab.player.view.PlayerView; -import com.huawei.codelab.player.view.SimplePlayerController; -import com.huawei.codelab.util.LogUtil; -import com.huawei.codelab.util.ScreenUtils; - -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.content.Intent; -import ohos.agp.components.DependentLayout; -import ohos.app.dispatcher.task.TaskPriority; -import ohos.bundle.AbilityInfo; - -/** - * SimplePlayerAbilitySlice - * - * @since 2021-04-04 - */ -public class SimplePlayerAbilitySlice extends AbilitySlice { - private static final String TAG = SimplePlayerAbilitySlice.class.getSimpleName(); - private ImplPlayer player; - private DependentLayout parentLayout; - private PlayerView playerView; - private PlayerLoading loadingView; - private SimplePlayerController controllerView; - private String url = "entry/resources/base/media/gubeishuizhen.mp4"; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_simple_video_play_layout); - player = new HmPlayer.Builder(this).setFilePath(url).create(); - player.getLifecycle().onStart(); - initComponent(); - } - - private void initComponent() { - if (findComponentById(ResourceTable.Id_parent) instanceof DependentLayout) { - parentLayout = (DependentLayout) findComponentById(ResourceTable.Id_parent); - } - if (findComponentById(ResourceTable.Id_player_view) instanceof PlayerView) { - playerView = (PlayerView) findComponentById(ResourceTable.Id_player_view); - } - if (findComponentById(ResourceTable.Id_loading_view) instanceof PlayerLoading) { - loadingView = (PlayerLoading) findComponentById(ResourceTable.Id_loading_view); - } - if (findComponentById(ResourceTable.Id_controller_view) instanceof SimplePlayerController) { - controllerView = (SimplePlayerController) findComponentById(ResourceTable.Id_controller_view); - } - playerView.bind(player); - loadingView.bind(player); - controllerView.bind(player); - } - - @Override - protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) { - super.onOrientationChanged(displayOrientation); - int screenWidth = ScreenUtils.getScreenWidth(this); - parentLayout.setWidth(screenWidth); - player.openGesture(displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE); - } - - @Override - public void onActive() { - super.onActive(); - getGlobalTaskDispatcher(TaskPriority.DEFAULT).delayDispatch(() -> player.play(), Constants.NUMBER_1000); - } - - @Override - public void onForeground(Intent intent) { - player.getLifecycle().onForeground(); - super.onForeground(intent); - } - - @Override - protected void onBackground() { - LogUtil.info(TAG, "onBackground is called"); - player.getLifecycle().onBackground(); - super.onBackground(); - } - - @Override - protected void onStop() { - LogUtil.info(TAG, "onStop is called"); - loadingView.unbind(); - controllerView.unbind(); - playerView.unbind(); - player.getLifecycle().onStop(); - super.onStop(); - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java deleted file mode 100644 index 2aa98e435c0ddbd243930d4a42aa81ef62eafc15..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/LogUtil.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; - -/** - * Log util - * - * @since 2021-04-04 - */ -public class LogUtil { - private static final String TAG_LOG = "LogUtil"; - - private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtil.TAG_LOG); - - private static final String LOG_FORMAT = "%{public}s: %{public}s"; - - private LogUtil() { - } - - /** - * Print debug log - * - * @param tag log tag - * @param msg log message - */ - public static void debug(String tag, String msg) { - HiLog.debug(LABEL_LOG, LOG_FORMAT, tag, msg); - } - - /** - * Print info log - * - * @param tag log tag - * @param msg log message - */ - public static void info(String tag, String msg) { - HiLog.info(LABEL_LOG, LOG_FORMAT, tag, msg); - } - - /** - * Print error log - * - * @param tag log tag - * @param msg log message - */ - public static void error(String tag, String msg) { - HiLog.error(LABEL_LOG, LOG_FORMAT, tag, msg); - } -} diff --git a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java b/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java deleted file mode 100644 index 1725ff685418af5a64d66d74e6637d4bbb62cbcf..0000000000000000000000000000000000000000 --- a/SimpleVideoCodelab/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.huawei.codelab.util; - -import ohos.agp.utils.Point; -import ohos.agp.window.service.Display; -import ohos.agp.window.service.DisplayManager; -import ohos.app.Context; -import ohos.global.configuration.DeviceCapability; - -import java.util.Optional; - -/** - * Screen util - * - * @since 2021-04-04 - */ -public class ScreenUtils { - private ScreenUtils() { - } - - /** - * getScreenHeight - * - * @param context context - * @return Screen Height - */ - public static int getScreenHeight(Context context) { - DisplayManager displayManager = DisplayManager.getInstance(); - Optional optDisplay = displayManager.getDefaultDisplay(context); - Point point = new Point(0, 0); - if (!optDisplay.isPresent()) { - return (int) point.position[1]; - } else { - Display display = optDisplay.get(); - display.getSize(point); - return (int) point.position[1]; - } - } - - /** - * getScreenWidth - * - * @param context context - * @return Screen Width - */ - public static int getScreenWidth(Context context) { - DisplayManager displayManager = DisplayManager.getInstance(); - Optional optDisplay = displayManager.getDefaultDisplay(context); - Point point = new Point(0, 0); - if (!optDisplay.isPresent()) { - return (int) point.position[0]; - } else { - Display display = optDisplay.get(); - display.getSize(point); - return (int) point.position[0]; - } - } - - /** - * dp2px - * - * @param context context - * @param size size - * @return int - */ - public static int dp2px(Context context, int size) { - int density = context.getResourceManager().getDeviceCapability().screenDensity / DeviceCapability.SCREEN_MDPI; - return size * density; - } - - /** - * px2dip - * - * @param context context - * @param size size - * @return int - */ - public static int px2dip(Context context, int size) { - int density = context.getResourceManager().getDeviceCapability().screenDensity / DeviceCapability.SCREEN_MDPI; - return size / density; - } -} diff --git a/StepsCard/README.md b/StepsCard/README.md index 3ed8768d36acd739b4510ee2552f92b2832227ce..7ac832aa126919500adb8fe16f810ded5ac0b1e7 100644 --- a/StepsCard/README.md +++ b/StepsCard/README.md @@ -11,13 +11,15 @@ 用户指南 • 下载此项目 -• 打开HUAWEI DevEco Studio,单击File> Open选择此ComponentCodelab +• 打开HUAWEI DevEco Studio,单击File> Open选择此StepsCard • 单击Build> Build App(s)/Hap(s)>Build Debug Hap(s)以编译hap软件包 • 单击Run> Run 'entry'以运行hap包 注意 • 您可以选择在模拟器或真机上运行hap软件包。 • 如果在真机上运行它,则需要在项目的File> Project Structure> Modules> Signing Configs中配置签名和证书信息。 +• 由于目前暂无办法保证卡片服务不被系统销毁,需要通过手机管家> 应用启动管理> 计步器服务卡片> 点击右侧滑块> 选择开启“允许后台活动”开启后台运行权限,如需要也可开启“运行自启动”。 + 许可 请参阅LICENSE文件以获得更多信息。 @@ -41,6 +43,7 @@ User guide Note • You can choose to run the hap package on the simulator or the phone. • If you run it on the phone, you need to configure the signature and certificate information in the project's File> Project Structure> Modules> Signing Configs. +• Currently, there is no way to ensure that the card service will not be destroyed by the system. Go to Phone Manager > App Startup Management > Pedometer Service Card, touch the slider on the right, and select Enable Background Activities to enable the background running permission. You can also enable Auto Start if necessary. Licensing Please see LICENSE for more info. \ No newline at end of file diff --git a/StepsCard/entry/src/main/config.json b/StepsCard/entry/src/main/config.json index 08c6a8c35400452cf799950f24a83b4e3c15381c..de827ac8116a244a85046c19c20617cacbb63c91 100644 --- a/StepsCard/entry/src/main/config.json +++ b/StepsCard/entry/src/main/config.json @@ -31,9 +31,20 @@ "reason": "get step count", "usedScene": { "ability": [ - ".MainAbility" + ".MainAbility", + ".StepSensorService" ], - "when": "inuse" + "when": "always" + } + }, + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "reason": "keep service ability backgroud running", + "usedScene": { + "ability": [ + ".StepSensorService" + ], + "when": "always" } } ], @@ -64,7 +75,11 @@ "icon": "$media:icon", "description": "$string:stepsensorservice_description", "type": "service", - "visible": false + "visible": true, + "backgroundModes": [ + "dataTransfer", + "location" + ] }, { "orientation": "unspecified", @@ -74,7 +89,7 @@ "label": "$string:app_name", "type": "page", "launchType": "standard", - "visible": false, + "visible": true, "formsEnabled": true, "forms": [ { @@ -90,7 +105,7 @@ "2*2" ], "updateEnabled": true, - "updateDuration": 1 + "updateDuration": 30 }, { "jsComponentName": "card2X4", @@ -105,7 +120,7 @@ "2*4" ], "updateEnabled": true, - "updateDuration": 1 + "updateDuration": 30 } ] } diff --git a/StepsCard/entry/src/main/java/com/huawei/cookbook/StepSensorService.java b/StepsCard/entry/src/main/java/com/huawei/cookbook/StepSensorService.java index e7884de18607c983899912404cea0d51673e4011..02be164d41b9d43c7cda9a0af04cf3fe0faf7b08 100644 --- a/StepsCard/entry/src/main/java/com/huawei/cookbook/StepSensorService.java +++ b/StepsCard/entry/src/main/java/com/huawei/cookbook/StepSensorService.java @@ -31,6 +31,7 @@ import ohos.aafwk.content.Intent; import ohos.data.DatabaseHelper; import ohos.data.orm.OrmContext; import ohos.data.orm.OrmPredicates; +import ohos.event.notification.NotificationRequest; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; import ohos.eventhandler.InnerEvent; @@ -49,7 +50,8 @@ import java.util.List; */ public class StepSensorService extends Ability { private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo"); - private static final long INTERVAL = 100000000L; + private static final long INTERVAL = 3000000000L; + private static final int NOTICE_ID = 1005; private CategoryMotionAgent categoryMotionAgent = new CategoryMotionAgent(); private ICategoryMotionDataCallback categoryMotionDataCallback; private CategoryMotion categoryMotion; @@ -59,7 +61,7 @@ public class StepSensorService extends Ability { @Override public void onStart(Intent intent) { - HiLog.error(LABEL_LOG, "StepSensorService::onStart"); + HiLog.info(LABEL_LOG, "StepSensorService::onStart"); super.onStart(intent); connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class); myHandler = new MyEventHandler(EventRunner.getMainEventRunner()); @@ -68,6 +70,8 @@ public class StepSensorService extends Ability { public void onSensorDataModified(CategoryMotionData categoryMotionData) { float[] values = categoryMotionData.getValues(); handleSensorData(values[0]); + // 设置通知 + notice(values[0]); } @Override @@ -84,6 +88,22 @@ public class StepSensorService extends Ability { } } + // 前台service + private void notice(float stepValue) { + // 创建通知 + NotificationRequest request = new NotificationRequest(NOTICE_ID); + request.setAlertOneTime(true); + NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent(); + SensorData sensorData = DatabaseUtils.getSensorData(connect, DateUtils.getDate(0)); + if (sensorData != null) { + content.setText("今天走了" + sensorData.getStepsValue() + "步"); + } + NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content); + request.setContent(notificationContent); + // 绑定通知 + keepBackgroundRunning(NOTICE_ID, request); + } + /** * handle sensor data * @@ -99,11 +119,12 @@ public class StepSensorService extends Ability { @Override public void run() { // 存储数据 - DatabaseUtils.insertValues(realValue, connect); + DatabaseUtils.insertValues(realValue, value, connect); // 更新页面 MainAbilitySlice.updatePage(stringValue); // 更新卡片 updateForms(stringValue); + } }); } @@ -164,4 +185,10 @@ public class StepSensorService extends Ability { super.processEvent(event); } } + + @Override + public void onMemoryLevel(int level) { + HiLog.info(LABEL_LOG, "StepSensorService::level::" + level); + super.onMemoryLevel(level); + } } \ No newline at end of file diff --git a/StepsCard/entry/src/main/java/com/huawei/cookbook/database/SensorData.java b/StepsCard/entry/src/main/java/com/huawei/cookbook/database/SensorData.java index 9ba2517b26228344cc9dbe1ebb3c8cac05144319..e93ec890dbdf6e098dd05444414db270aff039e0 100644 --- a/StepsCard/entry/src/main/java/com/huawei/cookbook/database/SensorData.java +++ b/StepsCard/entry/src/main/java/com/huawei/cookbook/database/SensorData.java @@ -31,6 +31,9 @@ public class SensorData extends OrmObject { // stepsValue private int stepsValue; + // 实际步数 + private int realValue; + public SensorData() { } @@ -39,10 +42,12 @@ public class SensorData extends OrmObject { * * @param date date * @param stepsValue stepsValue + * @param realValue */ - public SensorData(String date, int stepsValue) { + public SensorData(String date, int stepsValue, int realValue) { this.date = date; this.stepsValue = stepsValue; + this.realValue = realValue; } public String getDate() { @@ -60,4 +65,12 @@ public class SensorData extends OrmObject { public void setStepsValue(int stepsValue) { this.stepsValue = stepsValue; } + + public int getRealValue() { + return realValue; + } + + public void setRealValue(int realValue) { + this.realValue = realValue; + } } diff --git a/StepsCard/entry/src/main/java/com/huawei/cookbook/slice/MainAbilitySlice.java b/StepsCard/entry/src/main/java/com/huawei/cookbook/slice/MainAbilitySlice.java index ed8dea7cfb16f28784098afaebadb5f8629a81c5..8b5f63fb7c20b958788a37aea042798ed323f39b 100644 --- a/StepsCard/entry/src/main/java/com/huawei/cookbook/slice/MainAbilitySlice.java +++ b/StepsCard/entry/src/main/java/com/huawei/cookbook/slice/MainAbilitySlice.java @@ -80,7 +80,7 @@ public class MainAbilitySlice extends AbilitySlice implements PermissionBridge.O Operation operation = new Intent.OperationBuilder() .withDeviceId("") .withBundleName(getBundleName()) - .withAbilityName(StepSensorService.class.getSimpleName()) + .withAbilityName(StepSensorService.class.getName()) .build(); intentService.setOperation(operation); startAbility(intentService); diff --git a/StepsCard/entry/src/main/java/com/huawei/cookbook/utils/DatabaseUtils.java b/StepsCard/entry/src/main/java/com/huawei/cookbook/utils/DatabaseUtils.java index 01db9ff779c6a598c2b19cdfc293599698363d0c..ead2363848a0c8ce76556332dd976cff8c80cf63 100644 --- a/StepsCard/entry/src/main/java/com/huawei/cookbook/utils/DatabaseUtils.java +++ b/StepsCard/entry/src/main/java/com/huawei/cookbook/utils/DatabaseUtils.java @@ -67,10 +67,11 @@ public class DatabaseUtils { * * @param value 数据 * @param connect 数据连接 + * @param realValue 真实传感器数据 */ - public static void insertValues(float value, OrmContext connect) { + public static void insertValues(float value, float realValue, OrmContext connect) { String now = DateUtils.getDate(0); - SensorData sensorData = new SensorData(now, (int) value); + SensorData sensorData = new SensorData(now, (int) value, (int) realValue); // 查询今天是否有数据 SensorData todayData = getSensorData(connect, now); boolean isInsert = false; @@ -100,9 +101,9 @@ public class DatabaseUtils { List datas = connect.query(ormPredicates); SensorData sensorData = null; if (datas.size() > 0) { - sensorData = new SensorData(now, (int) (value - datas.get(0).getStepsValue())); + sensorData = new SensorData(now, (int) (value - datas.get(0).getRealValue()), (int) value); } else { - sensorData = new SensorData(now, (int) value); + sensorData = new SensorData(now, (int) value, (int) value); } return sensorData; } @@ -133,8 +134,11 @@ public class DatabaseUtils { */ public static List getLastFourDaysValue(OrmContext connect) { List results = new ArrayList<>(SHOW_DAYS); - OrmPredicates ormPredicates = new OrmPredicates(SensorData.class); + OrmPredicates ormPredicates = connect.where(SensorData.class); + + List datas1 = connect.query(ormPredicates); for (int i = SHOW_DAYS; i > 0; i--) { + ormPredicates.clear(); ormPredicates.equalTo(DATA_FILED_DATE, DateUtils.getDate(i)); List datas = connect.query(ormPredicates); if (datas.size() == 0) { diff --git a/StepsCard/entry/src/main/js/card2X2/pages/index/index.css b/StepsCard/entry/src/main/js/card2X2/pages/index/index.css index d9d8720602568948af3a77e5a0d21923c2da35c0..ee57e5ddb8e52645b4d3133a0ccb5e0c339e4f18 100644 --- a/StepsCard/entry/src/main/js/card2X2/pages/index/index.css +++ b/StepsCard/entry/src/main/js/card2X2/pages/index/index.css @@ -40,7 +40,6 @@ font-weight: bold; color: #F3F6F5; font-size: 16px; - } .item_content {/* width: 154px;*/ diff --git a/StepsCard/entry/src/main/js/card2X4/pages/index/index.css b/StepsCard/entry/src/main/js/card2X4/pages/index/index.css index 598ecad0efa92741ecb20dc264599d0b310d86cc..59de6256bf027ad60029032ec7047ad5361c6296 100644 --- a/StepsCard/entry/src/main/js/card2X4/pages/index/index.css +++ b/StepsCard/entry/src/main/js/card2X4/pages/index/index.css @@ -32,7 +32,6 @@ align-content: flex-start; position: relative; top: 5; - } .left_items_center { diff --git a/StepsCard/entry/src/main/js/card2X4/pages/index/index.js b/StepsCard/entry/src/main/js/card2X4/pages/index/index.js index 0b5c8ee9c7133cf2da0813a637cc9d6886190b62..0e94875b132824ccf1b1aef6ea5c64532c575b0a 100644 --- a/StepsCard/entry/src/main/js/card2X4/pages/index/index.js +++ b/StepsCard/entry/src/main/js/card2X4/pages/index/index.js @@ -71,7 +71,7 @@ export default { } }, steps: 0, - percent: 20, + percent: 0, mileage: 0 }, diff --git a/StepsCard/entry/src/main/resources/base/element/string.json b/StepsCard/entry/src/main/resources/base/element/string.json index d847b4d265fbdae96e94da2a617d12b887fd85ab..dfa769a5d118ac0d2dac9a2119cc8ecaddb84574 100644 --- a/StepsCard/entry/src/main/resources/base/element/string.json +++ b/StepsCard/entry/src/main/resources/base/element/string.json @@ -2,7 +2,7 @@ "string": [ { "name": "app_name", - "value": "StepsCard" + "value": "计步器服务卡片" }, { "name": "mainability_description", @@ -19,10 +19,6 @@ { "name": "stepformability_description", "value": "Java_Phone_Empty Feature Ability" - }, - { - "name": "HelloWorld", - "value": "Hello World" } ] } \ No newline at end of file