拥有只属于你的音乐app,是一种什么体验? - HarmonyOS技术社区 - 电子技术论坛 - 广受欢迎的专业电子论坛
分享 收藏 返回

[文章]

拥有只属于你的音乐app,是一种什么体验?

不知道有没有同学遇到过这种场景,和好朋友一起出去游玩时,坐在地铁或公交车上,每当听到一首好听的歌曲,总是忍不住和身边的伙伴一起分享,于是和同学每人戴着一只耳机共用一只手机听,这种方式难免会影响听歌的质感。在这种情况下,想到了使用服务流转开发一款“一起听吧”app,这样就可以和身边的朋友一起听好听的音乐了,可以同时间体会到的高低起伏优美动听的音乐,还能进行歌曲切换,是不是还挺不错。

言归正传,接下来就开始介绍“一起听吧”应用开发的功能。 该应用使用服务流转方式实现,流转:在HarmonyOS中泛指多设备分布式操作。流转能力打破设备界限,多设备联动,使用户应用程序可分可合、可流转。流转按照体验可分为跨端迁移(指在A端运行的FA迁移到B端上,完成迁移后, B端FA继续任务,而A端应用退出)和多端协同(指多端上的不同FA/PA同时运行、或者交替运行实现完整的业务)。可以说开发者站在了巨人的肩膀上创造更多可能,在此对HarmonyOS系统工程师们表示最真挚的崇拜。

开发准备
  • 万丈高楼平地起, 开始前请参考下载与安装软件、配置开发环境,完成DevEco Studio的安装和开发环境配置。
  • 开发环境配置完成后,请参考创建和运行Hello World创建工程
接下来就从创建工程项目开始介绍

创建一个新工程
  • 打开DevEco Studio,在欢迎页点击Create Project,创建一个新工程。
  • 根据工程创建向导,选择需要的Ability工程模板,然后点击Next。关于工程模板的介绍和支持的设备类型,请参考工程模板和开发语言介绍。



填写工程相关信息,Device Type选择Phone,Language选择Java ,其他保持默认值即可,点击Finish。关于各个参数的详细介绍,请参考创建一个新的工程。



工程创建完成后,DevEco Studio会自动进行工程的同步

使用模拟器运行HelloWorld
DevEco Studio提供远程模拟器和本地模拟器,本示例以远程模拟器为例进行说明。关于本地模拟器的使用请参考1.6.1-使用Local Emulator运行应用。

DevEco Studio提供模拟器供开发者运行和调试HarmonyOS应用。

  • 在DevEco Studio菜单栏,点击Tools > Device Manager。
  • 在Remote Emulator页签中点击Login,在浏览器中弹出华为开发者联盟帐号登录界面,请输入已实名认证的华为开发者联盟帐号的用户名和密码进行登录(查看远程模拟器登录常见问题)。
  • 登录后,请点击界面的允许按钮进行授权。


  • 在设备列表中,选择Phone设备P40,并点击▶按钮,运行模拟器(此处选择Super Device)


  • 点击DevEco Studio工具栏中的▶按钮运行工程,或使用默认快捷键Shift+F10(Mac为Control+R)运行工程


  • DevEco Studio会启动应用的编译构建,完成后应用即可运行在模拟器上


编写第一个页面
在Java UI框架中,提供了两种编写布局的方式:在XML中声明UI布局和在代码中创建布局。这两种方式创建出的布局没有本质差别,为了熟悉两种方式,我们将通过XML的方式编写第一个页面。

  • 在Project窗口,点击“entry > src > main > resources > base > layout”,打开“ability_main.xml”文件。


  • 第一个页面内有一个HarmonyOS图标和一个按钮,使用DependentLayout布局,通过DependentLayout 和Button组件来实现,其中vp和fp分别表示虚拟像素和字体像素。“ability_main.xml”的示例代码如下:
  1. tionalLayout
  2.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  3.     ohos:height="match_parent"
  4.     ohos:width="match_parent"
  5.     ohos:orientation="vertical"
  6.     ohos:background_element="$media:black">
  7.    
  8.         ohos:height="360vp"
  9.         ohos:width="380vp"
  10.         ohos:alignment="center"
  11.         ohos:top_margin="100vp"
  12.         ohos:background_element="$media:harmonyos_logo">
  13.    

  14.    
  15.         ohos:id="$+id:music_play_control_container"
  16.         ohos:weight="1"
  17.         ohos:height="0vp"
  18.         ohos:width="match_parent"
  19.         ohos:alignment="center"
  20.         ohos:bottom_margin="80vp"
  21.         ohos:start_padding="10vp"
  22.         ohos:end_padding="10vp"
  23.         ohos:top_margin="100vp">
  24.         
  25.             ohos:id="$+id:btn_music"
  26.             ohos:height="100vp"
  27.             ohos:width="300vp"
  28.             ohos:background_element="$graphic:background_button"
  29.             ohos:text_color="$color:white"
  30.             ohos:layout_alignment="horizontal_center"
  31.             ohos:text_alignment="center"
  32.             ohos:left_padding="15vp"
  33.             ohos:right_padding="15vp"
  34.             ohos:text="$string:btn_into_page"
  35.             ohos:text_size="30vp"
  36.             ohos:top_margin="20vp">
  37.         

  38.    


  • 页面预览效果:


  • 在XML文件中添加组件后,需要在Java代码中加载XML布局。在Project窗口,选择“entry > src > main > java > com.luxiaolu.musictogether > slice” ,打开“MainAbilitySlice.java”文件,使用setUIContent方法加载“ability_main.xml”布局,同时在该Ability中检查相关权限,MainAbilitySlice.java源码如下:
  1. public class MainAbilitySlice extends AbilitySlice {
  2.     private static final String TAG = CommonData.TAG + MainAbilitySlice.class.getSimpleName();

  3.     private static final int PERMISSION_CODE = 10000000;

  4.     @Override
  5.     public void onStart(Intent intent) {
  6.         super.onStart(intent);
  7.         super.setUIContent(ResourceTable.Layout_ability_main);
  8.         grantPermission();
  9.         initView();
  10.     }

  11.     void grantPermission() {
  12.         if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
  13.             if (canRequestPermission(DISTRIBUTED_DATASYNC)) {
  14.                 requestPermissionsFromUser(new String[] {DISTRIBUTED_DATASYNC}, PERMISSION_CODE);
  15.             }
  16.         }
  17.     }

  18.     private void initView() {
  19.         findComponentById(ResourceTable.Id_btn_music).setClickedListener(new ButtonClick());
  20.     }

  21.     private void TogetherMusic() {
  22.         LogUtil.info(TAG, "Click ResourceTable Id_togetherMusic");
  23.         Intent musicIntent = new Intent();
  24.         Operation operationMusic = new Intent.OperationBuilder().withBundleName(getBundleName())
  25.                 .withAbilityName(CommonData.ABILITY_MAIN)
  26.                 .withAction(CommonData.MUSIC_PAGE)
  27.                 .build();
  28.         musicIntent.setOperation(operationMusic);
  29.         startAbility(musicIntent);
  30.     }
  31.    
  32.     /**
  33.      * ButtonClick
  34.      */
  35.     private class ButtonClick implements Component.ClickedListener {
  36.         @Override
  37.         public void onClick(Component component) {
  38.             int btnId = component.getId();
  39.             switch (btnId) {
  40.                 case ResourceTable.Id_btn_music:
  41.                     TogetherMusic();
  42.                     break;
  43.                 default:
  44.                     LogUtil.info(TAG, "Click default");
  45.                     break;
  46.             }
  47.         }
  48.     }
  49. }

5.第二个页面实现音乐播放页面,创建顺序和第一个页面方式相同,可以使用复制修改的方式添加,依然使用DependentLayout布局,通过Text和Image,RoundProgressBar,Slider来实现, ability_music.xml 代码如下:

  1.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  2.     ohos:id="$+id:play_music_root"
  3.     ohos:height="match_parent"
  4.     ohos:width="match_parent"
  5.     ohos:background_element="$media:black2"
  6.     ohos:orientation="vertical">

  7.    
  8.         ohos:height="match_content"
  9.         ohos:width="match_parent"
  10.         ohos:alignment="center"
  11.         ohos:orientation="vertical"
  12.         ohos:top_margin="50vp">

  13.         
  14.             ohos:id="$+id:music_name"
  15.             ohos:height="match_content"
  16.             ohos:width="match_content"
  17.             ohos:bottom_margin="10vp"
  18.             ohos:text="$string:video_name"
  19.             ohos:text_alignment="center"
  20.             ohos:text_color="#FFFFFF"
  21.             ohos:text_size="34fp"
  22.             />
  23.    

  24.    
  25.         ohos:height="0vp"
  26.         ohos:width="match_parent"
  27.         ohos:alignment="center"
  28.         ohos:weight="1">

  29.         
  30.             ohos:id="$+id:music_posters"
  31.             ohos:height="match_content"
  32.             ohos:image_src="$media:cd_music2"
  33.             ohos:width="match_content"
  34.             ohos:visibility="hide"
  35.             />

  36.         
  37.             ohos:id="$+id:progressCircularImage"
  38.             ohos:height="250vp"
  39.             ohos:width="250vp"
  40.             ohos:progress="1"
  41.             ohos:progress_width="0vp"
  42.             ohos:progress_color="$color:default_transparent"
  43.             ohos:background_element="$media:cd_music1"
  44.             ohos:max="100"
  45.             ohos:min="0"
  46.             />
  47.    

  48.    
  49.         ohos:id="$+id:progress_container"
  50.         ohos:height="match_content"
  51.         ohos:width="match_parent"
  52.         ohos:start_margin="20vp"
  53.         ohos:orientation="vertical"
  54.         ohos:end_margin="20vp"
  55.         ohos:top_margin="37.25vp">

  56.         
  57.             ohos:height="match_parent"
  58.             ohos:width="match_parent"
  59.             ohos:orientation="horizontal">

  60.             
  61.                 ohos:id="$+id:play_progress_time"
  62.                 ohos:height="match_content"
  63.                 ohos:width="match_content"
  64.                 ohos:layout_alignment="vertical_center"
  65.                 ohos:end_margin="10vp"
  66.                 ohos:start_margin="0vp"
  67.                 ohos:text="$string:play_time"
  68.                 ohos:text_alignment="center"
  69.                 ohos:text_color="#FFCCE7FF"
  70.                 ohos:text_size="13vp"/>

  71.             
  72.                 ohos:height="match_content"
  73.                 ohos:width="0vp"
  74.                 ohos:weight="1"/>

  75.             
  76.                 ohos:id="$+id:play_total_time"
  77.                 ohos:height="match_content"
  78.                 ohos:width="match_content"
  79.                 ohos:layout_alignment="vertical_center"
  80.                 ohos:end_margin="10vp"
  81.                 ohos:start_margin="0vp"
  82.                 ohos:text="$string:play_time"
  83.                 ohos:text_alignment="center"
  84.                 ohos:text_color="#FFCCE7FF"
  85.                 ohos:text_size="13vp"/>
  86.         

  87.         
  88.             ohos:id="$+id:play_progress_bar"
  89.             ohos:height="14vp"
  90.             ohos:width="match_parent"
  91.             ohos:background_instruct_element="#64CCE7FF"
  92.             ohos:layout_alignment="vertical_center"
  93.             ohos:progress_color="#FFCCE7FF"
  94.             ohos:weight="1"/>

  95.    

  96.    
  97.         ohos:id="$+id:music_play_control_container"
  98.         ohos:height="72vp"
  99.         ohos:width="match_parent"
  100.         ohos:bottom_margin="80vp"
  101.         ohos:start_padding="10vp"
  102.         ohos:orientation="horizontal"
  103.         ohos:end_padding="10vp"
  104.         ohos:top_margin="40vp">

  105.         
  106.             ohos:id="$+id:control_box"
  107.             ohos:height="match_content"
  108.             ohos:width="match_content"
  109.             ohos:layout_alignment="center"
  110.             ohos:orientation="vertical"
  111.             ohos:weight="1">

  112.             
  113.                 ohos:id="$+id:remote_play"
  114.                 ohos:height="48vp"
  115.                 ohos:width="48vp"
  116.                 ohos:background_element="$graphic:button_bg"
  117.                 ohos:image_src="$media:remote_play_selected"
  118.                 ohos:layout_alignment="center"
  119.                 ohos:scale_mode="inside"/>
  120.         

  121.         
  122.             ohos:id="$+id:control_box2"
  123.             ohos:height="match_content"
  124.             ohos:width="match_content"
  125.             ohos:layout_alignment="center"
  126.             ohos:orientation="vertical"
  127.             ohos:weight="1">

  128.             
  129.                 ohos:id="$+id:music_play_prev_btn"
  130.                 ohos:height="48vp"
  131.                 ohos:width="48vp"
  132.                 ohos:background_element="$graphic:button_bg"
  133.                 ohos:image_src="$media:ic_himusic_previous"
  134.                 ohos:layout_alignment="center"
  135.                 ohos:scale_mode="inside"/>
  136.         

  137.         
  138.             ohos:id="$+id:control_box3"
  139.             ohos:height="match_content"
  140.             ohos:width="match_content"
  141.             ohos:layout_alignment="center"
  142.             ohos:orientation="vertical"
  143.             ohos:weight="1">

  144.             
  145.                 ohos:id="$+id:music_play_btn"
  146.                 ohos:height="48vp"
  147.                 ohos:width="48vp"
  148.                 ohos:background_element="$graphic:button_bg"
  149.                 ohos:image_src="$media:ic_himusic_play"
  150.                 ohos:layout_alignment="center"
  151.                 ohos:scale_mode="inside"/>
  152.         

  153.         
  154.             ohos:id="$+id:control_box4"
  155.             ohos:height="match_content"
  156.             ohos:width="match_content"
  157.             ohos:layout_alignment="center"
  158.             ohos:orientation="vertical"
  159.             ohos:weight="1">

  160.             
  161.                 ohos:id="$+id:music_play_next_btn"
  162.                 ohos:height="48vp"
  163.                 ohos:width="48vp"
  164.                 ohos:background_element="$graphic:button_bg"
  165.                 ohos:image_src="$media:ic_himusic_next"
  166.                 ohos:layout_alignment="center"
  167.                 ohos:scale_mode="inside"/>
  168.         

  169.    

  • 预览效果图:


  • MusicAbilitySlice.java是业务逻辑主代码,实现多设备连接,音乐播放/暂停,上下歌曲切换和音乐播放时动态图片旋转效果实现功能1)、 查找在线设备,并选择设备连接
  1. /**
  2. * 播放音乐时的动画效果(定时循环旋转图片)
  3. */
  4. private RoundProgressBar roundProgressBar;
  5. private PixelMapElement element;
  6. private int rotateDegrees =0;
  7. private int progressValue = 0;
  8. private int maxProgressVale = 100;

  9. private void initMyImage(){
  10.     roundProgressBar = (RoundProgressBar) findComponentById(ResourceTable.Id_progressCircularImage);
  11.     roundProgressBar.setMaxValue(maxProgressVale);
  12.     Timer timer = new Timer();
  13.     timer.schedule(new TimerTask(){
  14.         @Override
  15.         public void run() {
  16.             if(isPlaying){
  17.                 // 背景图片旋转角度
  18.                 if(rotateDegrees<360){
  19.                     // 每秒旋转角度
  20.                     rotateDegrees +=10;
  21.                 }else{
  22.                     rotateDegrees =0;
  23.                 }
  24.                 // 进度变化
  25.                 if(maxProgressVale>progressValue){
  26.                     progressValue +=10;
  27.                 }else {
  28.                     progressValue = 0;
  29.                 }
  30.                 element =  new PixelMapElement(transIdToPixelMap(rotateDegrees, resoureId,250,250));
  31.                 element.setFilterPixelMap(true);
  32.                 getUITaskDispatcher().asyncDispatch(new Runnable() {
  33.                     @Override
  34.                     public void run() {
  35.                         // 设置进度
  36.                         roundProgressBar.setProgressValue(progressValue);
  37.                         // 进度条背景图片
  38.                         roundProgressBar.setBackground(element);
  39.                     }
  40.                 });
  41.             }
  42.         }

  43.     },0,200);
  44. }

  45. // 将本地图片resId转换成PixelMap
  46. private PixelMap transIdToPixelMap(int rotateDegrees, int resId, int width, int height) {
  47.     InputStream source = null;
  48.     ImageSource imageSource = null;
  49.     try {
  50.         source = getContext().getResourceManager().getResource(resId);
  51.         imageSource = ImageSource.create(source, null);
  52.         ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
  53.         decodingOpts.desiredSize = new Size(width, height);
  54.         decodingOpts.rotateDegrees = rotateDegrees;
  55.         return imageSource.createPixelmap(decodingOpts);

  56.     } catch (IOException | NotExistException e) {
  57.         LogUtil.error(TAG, "getPixelMap error");
  58.     } finally {
  59.         try {
  60.             source.close();
  61.         } catch (IOException e) {
  62.             LogUtil.error(TAG, "getPixelMap source close error");
  63.         }
  64.     }
  65.     return PixelMap.create(null);
  66. }
  67. 2)、启动远程FA/PA 设备A连接设备B侧的PA,利用连接关系调用该PA执行特定任务
    private void connectRemotePa(String deviceId, int requestType) {
  68.     if (!deviceId.isEmpty()) {
  69.         Intent connectPaIntent = new Intent();
  70.         Operation operation = new Intent.OperationBuilder().withDeviceId(deviceId)
  71.                 .withBundleName(getBundleName())
  72.                 .withAbilityName(CommonData.MUSIC_SERVICE_NAME)
  73.                 .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
  74.                 .build();
  75.         connectPaIntent.setOperation(operation);
  76.         conn = new IAbilityConnection() {
  77.             @Override
  78.             public void onAbilityConnectDone(ElementName elementName, IRemoteObject remote, int resultCode) {
  79.                 LogUtil.info(TAG, "onAbilityConnectDone......");
  80.                 connectAbility(elementName, remote, requestType);
  81.             }
  82.             @Override
  83.             public void onAbilityDisconnectDone(ElementName elementName, int resultCode) {
  84.                 disconnectAbility(this);
  85.                 LogUtil.info(TAG, "onAbilityDisconnectDone......");
  86.             }
  87.         };
  88.         isConnected = getContext().connectAbility(connectPaIntent, conn);
  89.     }
  90. }

  91. private void connectAbility(ElementName elementName, IRemoteObject remote, int requestType) {
  92.     proxy = new MusicRemoteProxy(remote);
  93.     try {
  94.         proxy.senDataToRemote(requestType);
  95.     } catch (RemoteException e) {
  96.         LogUtil.error(TAG, "onAbilityConnectDone RemoteException");
  97.     }
  98. }
  99. 3)、在本地发起连接侧和对端被连接侧分别实现代理
    class MusicRemoteProxy implements IRemoteBroker {
  100.     private static final int ERR_OK = 0;
  101.     private static final int REQUEST_START_ABILITY = 1;
  102.     private static final int REQUEST_SEND_DATA = 2;
  103.     private final IRemoteObject remote;

  104.     MusicRemoteProxy(IRemoteObject remote) {
  105.         this.remote = remote;
  106.     }

  107.     @Override
  108.     public IRemoteObject asObject() {
  109.         return remote;
  110.     }

  111.     private void senDataToRemote(int requestType) throws RemoteException {
  112.         MessageParcel data = MessageParcel.obtain();
  113.         MessageParcel reply = MessageParcel.obtain();
  114.         try {
  115.             isLocal = false;
  116.             data.writeInt(actionFlag);
  117.             data.writeString(localDeviceId);
  118.             data.writeBoolean(isLocal);
  119.             MessageOption option = new MessageOption(MessageOption.TF_SYNC);
  120.             remote.sendRequest(requestType, data, reply, option);
  121.             LogUtil.info(TAG, "send action: "+actionFlag+"; isLocal: "+isLocal);
  122.             int ec = reply.readInt();
  123.             if (ec != ERR_OK) {
  124.                 LogUtil.error(TAG, "ec != ERR_OK RemoteException");
  125.             }
  126.         } catch (RemoteException e) {
  127.             LogUtil.error(TAG, "RemoteException");
  128.         } finally {
  129.             data.reclaim();
  130.             reply.reclaim();
  131.         }
  132.     }
  133. }

4)、 订阅事件(每个应用都可以订阅自己感兴趣的公共事件,订阅成功后且公共事件发布后,系统会把其发送给应用。这些公共事件可能来自系统、其他应用和应用自身)

公共事件相关基础类包含CommonEventData、CommonEventPublishInfo、CommonEventSubscribeInfo、CommonEventSubscriber和CommonEventManager

  1. /**
  2. * 订阅 接收事件
  3. */
  4. private void subscribe() {
  5.     MatchingSkills matchingSkills = new MatchingSkills();
  6.     matchingSkills.addEvent(CommonData.MUSIC_PALY_EVENT);
  7.     matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON);
  8.     CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
  9.     subscriber = new MyCommonEventSubscriber(subscribeInfo);
  10.     try {
  11.         LogUtil.info(TAG, "subscribeCommonEvent");
  12.         CommonEventManager.subscribeCommonEvent(subscriber);
  13.     } catch (RemoteException e) {
  14.         LogUtil.error(TAG, "subscribeCommonEvent occur exception.");
  15.     }
  16. }

  17. /**
  18. * 订阅公共事件
  19. */
  20. class MyCommonEventSubscriber extends CommonEventSubscriber {
  21.     MyCommonEventSubscriber(CommonEventSubscribeInfo info) {
  22.         super(info);
  23.     }

  24.     @Override
  25.     public void onReceiveEvent(CommonEventData commonEventData) {
  26.         reciveTime = System.currentTimeMillis();
  27.         LogUtil.info(TAG, "onReceiveEvent, sendTime - reciveTime is " + (sendTime - reciveTime));
  28.         if (Math.abs(sendTime - reciveTime) <= MAX_RECIVE_TIME) {
  29.             LogUtil.info(TAG, "almost at the same time, do not handle recive msg");
  30.             isShare = false;
  31.             new ToastDialog(getContext()).setText("操作冲突,后续独立").setAlignment(LayoutAlignment.CENTER).show();
  32.             return;
  33.         }
  34.         // 接收远程数据
  35.         Intent intent = commonEventData.getIntent();
  36.         updateDataInfo(intent);
  37.     }
  38. }

  39. private void updateDataInfo(Intent intent) {
  40.     if(null != intent){
  41.         actionFlag = intent.getIntParam(CommonData.KEY_MUSIC_ACTION_ID, 0);
  42.         getUITaskDispatcher().delayDispatch(this::actionFun, DELAY_TIME);
  43.     }
  44. }

  45. private void actionFun(){
  46.     if(100 == actionFlag){
  47.         playOrPause();
  48.     }else if(200 == actionFlag){
  49.         nextMusic();
  50.     }else if(300 == actionFlag){
  51.         prevMusic();
  52.     }
  53. }

5)、 播放音乐时显示图片动画效果(暂时使用定时器,循环旋转图片)

  1. /**
  2. * 播放音乐时的动画效果(定时循环旋转图片)
  3. */
  4. private RoundProgressBar roundProgressBar;
  5. private PixelMapElement element;
  6. private int rotateDegrees =0;
  7. private int progressValue = 0;
  8. private int maxProgressVale = 100;

  9. private void initMyImage(){
  10.     roundProgressBar = (RoundProgressBar) findComponentById(ResourceTable.Id_progressCircularImage);
  11.     roundProgressBar.setMaxValue(maxProgressVale);
  12.     Timer timer = new Timer();
  13.     timer.schedule(new TimerTask(){
  14.         @Override
  15.         public void run() {
  16.             if(isPlaying){
  17.                 // 背景图片旋转角度
  18.                 if(rotateDegrees<360){
  19.                     // 每秒旋转角度
  20.                     rotateDegrees +=10;
  21.                 }else{
  22.                     rotateDegrees =0;
  23.                 }
  24.                 // 进度变化
  25.                 if(maxProgressVale>progressValue){
  26.                     progressValue +=10;
  27.                 }else {
  28.                     progressValue = 0;
  29.                 }
  30.                 element =  new PixelMapElement(transIdToPixelMap(rotateDegrees, resoureId,250,250));
  31.                 element.setFilterPixelMap(true);
  32.                 getUITaskDispatcher().asyncDispatch(new Runnable() {
  33.                     @Override
  34.                     public void run() {
  35.                         // 设置进度
  36.                         roundProgressBar.setProgressValue(progressValue);
  37.                         // 进度条背景图片
  38.                         roundProgressBar.setBackground(element);
  39.                     }
  40.                 });
  41.             }
  42.         }

  43.     },0,200);
  44. }

  45. // 将本地图片resId转换成PixelMap
  46. private PixelMap transIdToPixelMap(int rotateDegrees, int resId, int width, int height) {
  47.     InputStream source = null;
  48.     ImageSource imageSource = null;
  49.     try {
  50.         source = getContext().getResourceManager().getResource(resId);
  51.         imageSource = ImageSource.create(source, null);
  52.         ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
  53.         decodingOpts.desiredSize = new Size(width, height);
  54.         decodingOpts.rotateDegrees = rotateDegrees;
  55.         return imageSource.createPixelmap(decodingOpts);

  56.     } catch (IOException | NotExistException e) {
  57.         LogUtil.error(TAG, "getPixelMap error");
  58.     } finally {
  59.         try {
  60.             source.close();
  61.         } catch (IOException e) {
  62.             LogUtil.error(TAG, "getPixelMap source close error");
  63.         }
  64.     }
  65.     return PixelMap.create(null);
  66. }

  • 图片旋转效果:


  • MusicServiceAbility.java 基于Service模板的Ability主要用于后台运行任务(建立远程连接,发送事件数据),但不提供用户交互界面。Service可由其他应用或Ability启动,即使用户切换到其他应用,Service仍将在后台继续运行。了解更多创建、启动、连接Service
  1. public class MusicServiceAbility extends Ability {
  2.     private static final String TAG = "####service";

  3.     private TogetherMusicRemote remote = new TogetherMusicRemote();

  4.     @Override
  5.     public void onStart(Intent intent) {
  6.         super.onStart(intent);
  7.         LogUtil.info(TAG, "MusicServiceAbility::onStart");
  8.     }

  9.     @Override
  10.     public void onBackground() {
  11.         super.onBackground();
  12.         LogUtil.info(TAG, "MusicServiceAbility::onBackground");
  13.     }

  14.     @Override
  15.     public void onStop() {
  16.         super.onStop();
  17.         LogUtil.info(TAG, "MusicServiceAbility::onStop");
  18.     }

  19.     @Override
  20.     protected IRemoteObject onConnect(Intent intent) {
  21.         super.onConnect(intent);
  22.         return remote.asObject();
  23.     }

  24.     @Override
  25.     public void onDisconnect(Intent intent) {
  26.         LogUtil.info(TAG, "MusicServiceAbility::onDisconnect");
  27.     }


  28.     /**
  29.      * 发送 点击播放、暂停、下一首音乐切换动作指令
  30.      * [url=home.php?mod=space&uid=3142012]@param[/url] playAction 播放动作指令
  31.      */
  32.     private void sendEvent(int playAction) {
  33.         try {
  34.             Intent intent = new Intent();
  35.             Operation operation = new Intent.OperationBuilder().withAction(CommonData.MUSIC_PALY_EVENT).build();
  36.             intent.setOperation(operation);
  37.             intent.setParam(CommonData.KEY_MUSIC_ACTION_ID, playAction);
  38.             CommonEventData eventData = new CommonEventData(intent);
  39.             CommonEventManager.publishCommonEvent(eventData);
  40.         } catch (RemoteException e) {
  41.             LogUtil.error(TAG, "publishCommonEvent occur exception.");
  42.         }
  43.     }

  44.     /**
  45.      * 建立远程连接
  46.      */
  47.     public class TogetherMusicRemote extends RemoteObject implements IRemoteBroker {
  48.         private static final int ERR_OK = 0;

  49.         private static final int REQUEST_START_ABILITY = 1;

  50.         private TogetherMusicRemote() {
  51.             super("TogetherMusicRemote");
  52.         }

  53.         @Override
  54.         public IRemoteObject asObject() {
  55.             return this;
  56.         }

  57.         @Override
  58.         public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
  59.             String remoteDeviceId = data.readString();
  60.             int playAction = data.readInt();
  61.             boolean isLocal = data.readBoolean();
  62.             reply.writeInt(ERR_OK);
  63.             if (code == REQUEST_START_ABILITY) {
  64.                 Intent secondIntent = new Intent();
  65.                 Operation operation = new Intent.OperationBuilder().withDeviceId("")
  66.                         .withBundleName(getBundleName())
  67.                         .withAbilityName(CommonData.ABILITY_MAIN)
  68.                         .withAction(CommonData.MUSIC_PAGE)
  69.                         .build();
  70.                 secondIntent.setParam(CommonData.KEY_REMOTE_DEVICEID, remoteDeviceId);
  71.                 secondIntent.setParam(CommonData.KEY_MUSIC_ACTION_ID, playAction);
  72.                 secondIntent.setParam(CommonData.KEY_IS_LOCAL, isLocal);
  73.                 secondIntent.setOperation(operation);
  74.                 startAbility(secondIntent);
  75.             } else {
  76.                 sendEvent(playAction);
  77.             }
  78.             return true;
  79.         }
  80.     }
  81. }

整体效果演示



希望有更多同学或朋友加入HarmonyOS, 提供更多新鲜的、新奇的idea。

作者简介:我是老王,一个从事鸿蒙开发的中年老吃货。关注我,每天和你聊点关于华为、鸿蒙认证的一些事儿。

更多回帖

×
发帖