当前位置:主页 > 查看内容

安卓VS鸿蒙第三方件切换宝典 V1.0

发布时间:2021-05-10 00:00| 位朋友查看

简介:想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区 https://harmonyos.51cto.com 众所周知,安卓应用开发经过这么多年的发展相对成熟和稳定,鸿蒙OS作为后来者兼容一个成熟的开发体系会节省很多推广和开发成本。但在实际开发中,代码层面……

想了解更多内容,请访问:

51CTO和华为官方战略合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

众所周知,安卓应用开发经过这么多年的发展相对成熟和稳定,鸿蒙OS作为后来者兼容一个成熟的开发体系会节省很多推广和开发成本。但在实际开发中,代码层面仍然有很多细节上的差异,会给初次开发人员造成困扰。

本宝典旨在汇总实际开发中第三方件接入时的代码差异,以期帮助开发人员更好的进行开发作业,由于目前接触的开发类型有限,所汇总的内容多少会有疏漏,后期我们会进一步完善和补全。

欢迎关注我们以及我们的专栏,方便您及时获得相关内容的更新。

※基础功能

1.获取屏幕分辨率

安卓:

  1. getWindowManager().getDefaultDisplay(); 

鸿蒙:

  1. Optional<Display>  
  2. display = DisplayManager.getInstance().getDefaultDisplay(this.getContext()); 
  3. Point pt = new Point(); 
  4. display.get().getSize(pt); 

2.隐藏标题栏TitleBar

安卓:

鸿蒙:

confi.json中添加如下描述:

  1. ""metaData"":{ 
  2.        ""customizeData"":[ 
  3.            { 
  4.                ""name""""hwc-theme""
  5.                ""value""""androidhwext:style/Theme.Emui.NoTitleBar""
  6.                ""extra"":"""" 
  7.             } 
  8.        ] 
  9.    } 

3.获取屏幕密度

安卓:

  1. Resources.getSystem().getDisplayMetrics().density 

鸿蒙:

  1. // 获取屏幕密度 
  2. Optional<Display>  
  3. display = DisplayManager.getInstance().getDefaultDisplay(this.getContext());         
  4. DisplayAttributes displayAttributes = display.get().getAttributes(); 
  5. //displayAttributes.xDpi; 
  6. //displayAttributes.yDpi; 

4.获取上下文

安卓:

  1. context 

鸿蒙:

  1. getContext() 

5.组件的父类

安卓:

  1. android.view.View; class ProgressBar extends View 

鸿蒙:

  1. class ProgressBar extends Component 

6.沉浸式显示

安卓:

鸿蒙:

A:在config.json ability 中添加

  1. "metaData"": { 
  2.   ""customizeData"": [ 
  3.     { 
  4.       ""extra""""""
  5.       ""name""""hwc-theme""
  6.       ""value""""androidhwext:style/Theme.Emui.Light.NoTitleBar"" 
  7.     } 
  8.   ] 

B:在AbilitySlice的onStart函数内增加如下代码,注意要在setUIContent之前。

  1. getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS); 

7.获取运行时权限

安卓:

  1. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1) 

鸿蒙:

  1. requestPermissionsFromUser( 
  2.         new String[]{""ohos.permission.READ_MEDIA""""ohos.permission.WRITE_MEDIA""""ohos.permission.READ_USER_STORAGE""""ohos.permission.WRITE_USER_STORAGE"",}, 1); 

※布局&组件

1.页面跳转(显示跳转)

安卓:

A.从A跳转至B,没有参数,并且不接收返回值

  1. Intent intent = new Intent(); 
  2.     intent.setClass(A.this, B.class); 
  3.     startActivity(intent); 

B.从A跳转至B,有参数,不接收返回值

  1. Intent intent = new Intent(this, B.class); 
  2.  intent.putExtra(""name""""lily""); 
  3.  startActivity(intent); 

C.从A跳转至B,有参数,接收返回值

  1. Intent intent = new Intent(this, B.class); 
  2. intent.putExtra(""name""""lily""); 
  3. startActivityForResult(intent, 2); 

鸿蒙:

A.从A跳转至B,没有参数,并且不接收返回值

  1. present(new BSlice(), new Intent()); 

B.从A跳转至B,有参数,不接收返回值

  1. Intent intent = new Intent(); 
  2.             Operation operation = new Intent.OperationBuilder() 
  3.                     .withDeviceId("""")                   .withBundleName(""com.test"")                    .withAbilityName(""com.test.BAbility""
  4.                     .build(); 
  5.             intent.setParam(""name"",""lily""); 
  6.             intent.setOperation(operation); 
  7.             startAbility(intent); 

C.从A跳转至B,有参数,接收返回值

  1. Intent intent = new Intent(); 
  2.             Operation operation = new Intent.OperationBuilder() 
  3.                     .withDeviceId("""")                    .withBundleName(""com.test"")                    .withAbilityName(""com.test.BAbility""
  4.                     .build(); 
  5.             intent.setParam(""name"",""lily""); 
  6.             intent.setOperation(operation); 
  7.             startAbilityForResult(intent,100); 

2.页面跳转(隐式跳转)

安卓:

A.配置

  1. <activity android:name="".B""
  2.             <intent-filter> 
  3.                 <action android:name=""com.hly.view.fling""/> 
  4.             </intent-filter> 
  5.         </activity> 

B.启动

  1. Intent intent = new Intent();               intent.setAction(""com.hly.view.fling"");                intent.putExtra(""key""""name"");                startActivity(intent); 

鸿蒙:

A.在config.json文件ability 中添加以下信息

  1. "skills"":[ 
  2.      { 
  3.         ""actions"":[ 
  4.             ""ability.intent.gotopage"" 
  5.             ] 
  6.     } 

B.在MainAbility的onStart函数中,增加页面路由

  1. addActionRoute( ""ability.intent.gotopage"", BSlice.class.getName()); 

C.跳转

  1. Intent intent = new Intent(); 
  2.             intent.setAction(""ability.intent.gotopage""); 
  3.             startAbility(intent); 

3.页面碎片

安卓:

  1. Fragment 

鸿蒙:

  1. Fraction 

A:Ability继承FractionAbility

B:获取Fraction调度器

  1. getFractionManager().startFractionScheduler() 

C:构造Fraction

D:调用调度器管理Fraction

  1. FractionScheduler.add() 
  2. FractionScheduler.remove() 
  3. FractionScheduler.replace() 

备注:

参考demo

https://www.jianshu.com/p/58558dc6673a"

4.从xml文件创建一个组件实例

安卓:

  1. LayoutInflater.from(mContext).inflate(R.layout.banner_viewpager_layout, null); 

鸿蒙:

  1. LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_main, nullfalse); 

5.组件自定义绘制

安卓:

  1. ImageView.setImageDrawable(Drawable drawable); 

并重写Drawable 的draw函数

鸿蒙:

  1. Component.addDrawTask(Component.DrawTask task); 

并实现Component.DrawTask接口的onDraw函数

6.自定义组件的自定义属性(在xml中使用)

安卓:

需要3步

A.在 values/attrs.xml,在其中编写 styleable 和 item 等标签元素。

B.在layout.xml中,增加

  1. xmln:app= ""http://schemas.android.com/apk/res/-auto"" 

C.在自定义组件的构造函数中,调用array.getInteger(R.styleable.***, 100);获取属性

鸿蒙:

只需2步

A. 在组件定义的layout.xml中增加 xmlns:app=""http://schemas.huawei.com/apk/res/ohos""

然后就可以使用app:***(***为任意字符串)来增加自定义属性了,为了区分建议加上组件名前缀。

B. 在自定义组件的带AttrSet参数的构造函数中,使用下面代码获取属性。attrSet.getAttr(""***"").get().getStringValue();

7.触摸事件

安卓:

  1. android.view.MotionEvent 

鸿蒙:

  1. ohos.multimodalinput.event.TouchEvent 

8.事件处理

安卓:

  1. android.os.Handler 

鸿蒙:

  1. ohos.eventhandler.EventHandler 

9.控件触摸事件回调

安卓:

  1. android.view.View.OnTouchListener 

鸿蒙:

  1. ohos.agp.components.Component. 
  2. TouchEventListener 

10.轮播图继承的父类

安卓:

  1. extends ViewPager 

鸿蒙:

  1. extends PageSlider 

11.实现监听轮播图组件事件

安卓:

  1. implements PageSlider.PageChangedListener 

鸿蒙:

  1. Implements OnPageChangedListener 

12.touch事件监听

安卓:

  1. 直接重写onTouchEvent 

鸿蒙:

  1. 继承 Component.TouchEventListener然后在构造方法中设置监听 setTouchEventListener(this::onTouchEvent);实现onTouchEvent 

13.获取点击事件的坐标点

安卓:

  1. event.getX(), event.getY() 

鸿蒙:

  1. MmiPoint point = touchEvent.getPointerPosition(touchEvent.getIndex()); 

14.调节滚轮中内容间距

安卓:

  1. setLineSpacingMultiplier(float f) 

鸿蒙:

  1. setSelectedNormalTextMarginRatio(float f) 

15.滚轮定位

安卓:

  1. setPosition 

鸿蒙:

  1. setValue 

16.Layout布局改变监听

安卓:

  1. View.OnLayoutChangeListener 

鸿蒙:

  1. Component.LayoutRefreshedListener 

17.组件容器

安卓:

  1. ViewGroup 

鸿蒙:

  1. ComponentContainer 

18.添加组件

安卓:

  1. addView() 

鸿蒙:

  1. addComponent() 

19.动态列表的适配器

安卓:

  1. extends RecyclerView.Adapter<> 

鸿蒙:

  1. extends RecycleItemProvider 

20.动态列表

安卓:

  1. RecyclerView 

鸿蒙:

  1. ListContainer 

21.文本域动态监听

安卓:

  1. TextWatcher 

鸿蒙:

  1. Component.ComponentStateChangedListener 

22.组件绘制自定义布局

安卓:

  1. 重写onLayout(boolean changed, int leftint topint rightint bottom) 

鸿蒙:

  1. 重写Component.LayoutRefreshedListener的onRefreshed方法 

23.List组件

安卓:

  1. ListView 

鸿蒙:

  1. ListContainer 

24.设置背景颜色

安卓:

  1. setBackgroundColor(maskColor); 

鸿蒙:

  1. // 创建背景元素 
  2. ShapeElement shapeElement = new ShapeElement(); 
  3. // 设置颜色 
  4. shapeElement.setRgbColor(new RgbColor(255, 0, 0)); 
  5. view.setBackground(shapeElement); 

25.可以在控件上、下、左、右设置图标,大小按比例自适应

安卓:

  1. setCompoundDrawablesWithIntrinsicBounds 

鸿蒙:

  1. setAroundElements 

26.RadioButton组件在xml中如何设置checked属性

安卓:

在xml中可以设置

鸿蒙:

  1. radioButton = findComponentById(); 
  2. radioButton.setChecked(true); 

备注:

sdk2.0后 xml中没有了checked属性,如果使用,可以在java代码中实现"

27.文本域动态监听

安卓:

  1. TextWatcher 

鸿蒙:

  1. Component.ComponentStateChangedListener 

28.颜色类

安卓:

  1. java.awt.Color 

鸿蒙:

  1. ohos.agb.colors.rgbcolor 

29.为ckeckbox或者Switch按钮设置资源图片

安卓:

鸿蒙:

  1. VectorElement vectorElement = new VectorElement(this, ResourceTable.Graphic_candy); 
  2. setBackground(vectorElement) 

30.子组件将拖拽事件传递给父组件

安卓:

鸿蒙:

注册setDraggedListener侦听,实现onDragPreAccept方法,再方法内根据拖拽方向判断是否需要父组件处理,如果需要则返回false,否则返回true

※资源管理

1.管理资源

安卓:

  1. AssertManager 

鸿蒙:

  1. ResourceManager 

2.获取应用的资源文件rawFile,并返回InputStream

安卓:

  1. getResources() 
  2.  
  3. AssetManager类 

鸿蒙:

  1. ResourceManager resourceManager = getContext().getResourceManager(); 
  2.         RawFileEntry rawFileEntry = resourceManager.getRawFileEntry(jsonFile); 
  3.         Resource resource = null
  4.         try { 
  5.             resource = rawFileEntry.openRawFile(); 
  6.         } catch (IOException e) { 
  7.             e.printStackTrace(); 
  8.         } 

备注:

  1. Resource是InputStream的子类,可以直接作为InputStream使用。" 

3.获取文件路径

安卓:

  1. Environment.getExternalStorageDirectory().getAbsolutePath() 

鸿蒙:

  1. 获取文档(DIRECTORY_DOCUMENTS)、下载(DIRECTORY_DOWNLOADS)、视频(DIRECTORY_MOVIES)、音乐(DIRECTORY_MUSIC)、图片(DIRECTORY_PICTURES) 
  2.  
  3. GetExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() 

※消息&多线程

1.事件循环器

安卓:

  1. android.os.Looper 

鸿蒙:

  1. EventRunner.create(true

备注:

有参数且为true,表示队列被托管,参数为false,或无参表示不被托管,需要eventRunner.run()调用

2.消息

安卓:

  1. android.os.Message 

鸿蒙:

  1. InnerEvent 

3.休眠

安卓:

  1. android.os.SystemClock.sleep() 

鸿蒙:

  1. ohos.miscservices.timeutility.time
  2. Time.sleep(int millesend) 

4.事件通知延迟消息

安卓:

  1. Handler.postDelayed(MESSAGE_LOGIN, 5000); 

鸿蒙:

  1. Handler.postTask(task, 5000); 

5.Intent传递参数

安卓:

  1. Intent.putExtra or add Bundle 

鸿蒙:

  1. Intent.setParam 

6.消息发送

安卓:

  1. Handler handler = new Handler,通过handlerMsg发消息 

鸿蒙:

  1. InnerEvent event1 = InnerEvent.get(eventId1, param, object); 
  2.         myHandler.sendEvent(event1, 0, Priority.IMMEDIATE); 

7.更新UI

安卓:

  1. class MyHandle extends Handler{ 
  2.        @Override 
  3.        public void handleMessage(Message msg) { 
  4.            super.handleMessage(msg); 
  5.            switch (msg.what) { 
  6.                case 1: 
  7.                    //更新UI的操作 
  8.                    break; 
  9.                default
  10.                    Break; 
  11.            } 
  12.        } 
  13.    } 

鸿蒙:

  1. abilitySlice.getUITaskDispatcher().asyncDispatch(() -> { 
  2.     //更新UI的操作 
  3. }); 

※图片处理

1.位图资源

安卓:

  1. Bitmap 

鸿蒙:

  1. PixelMap 

2.图像缩放,拉伸到视图边界

安卓:

  1. ImageView.ScaleType 
  2. image.setScaleType(ScaleType.FXY); 

鸿蒙:

  1. Image.ScaleMode 
  2. image.setScaleMode(Image.ScaleMode.STRETCH); 

3.List组件&内容适配器

安卓:

  1. ListView 
  2. extends BaeAdapter 
  3. ViewPage.setAdapter(BaeAdapter); 

鸿蒙:

  1. ListContainer 
  2. extends PageSlider 
  3. PageSlider.setProvider(PageSlider); 

4.图片显示组件

安卓:

  1. androidx.appcompat.widget.AppCompatImageView 
  2. Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId); 
  3. Image.setImageBitmap(bitmap); 

鸿蒙:

  1. ohos.agp.components.Image 

根据实际情况可传递其他参数

  1. ImageSource imageSource = ImageSource.create(file, new ImageSource.SourceOptions()); 
  2. pixelMap = imageSource.createPixelmap(new ImageSource.DecodingOptions()); 
  3. image.setPixelMap(pixelMap); 

5.图片填充整个控件

安卓:

  1. image.setScaleType(ScaleType.FXY); 

鸿蒙:

  1. image.setScaleMode(Image.ScaleMode.STRETCH); 

6.通过资源id获取位图

安卓:

  1. getBitmapFromDrawable 

鸿蒙:

  1. /** 
  2.     * 通过资源ID获取位图对象 
  3.     **/ 
  4.    private PixelMap getPixelMap(int resId) { 
  5.        InputStream drawableInputStream = null
  6.        try { 
  7.            drawableInputStream = getResourceManager().getResource(resId); 
  8.            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions(); 
  9.            sourceOptions.formatHint = ""image/png""
  10.            ImageSource imageSource = ImageSource.create(drawableInputStream, null); 
  11.            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); 
  12.            decodingOptions.desiredSize = new Size(0, 0); 
  13.            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0); 
  14.            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888; 
  15.            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions); 
  16.            return pixelMap; 
  17.        } catch (Exception e) { 
  18.            e.printStackTrace(); 
  19.        } finally { 
  20.            try { 
  21.                if (drawableInputStream != null) { 
  22.                    drawableInputStream.close(); 
  23.                } 
  24.            } catch (Exception e) { 
  25.                e.printStackTrace(); 
  26.            } 
  27.        } 
  28.        return null
  29.    } 

7.获取Gif图片帧

安卓:

需要自定frame类,通过decoder获取

鸿蒙:

  1. ImageSource.createPixelmap(int index, ImageSource.DecodingOptions opts) 

8.BMP位图裁剪

安卓:

  1. Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height) 

鸿蒙:

  1. PixelMap.create​(PixelMap source, Rect srcRegion, PixelMap.InitializationOptions opts) 

※视频播放

在视频播放窗口上层增加控件

安卓:

鸿蒙:

A.pinToTop设置false,保证其他控件与surfaceProvider在同一layout下,并且不能设置背景

B.增加以下代码设置顶部窗口透明

  1. WindowManager.getInstance().getTopWindow().get().setTransparent(true); 

※数据库

数据库获取索引

安卓:

  1. android.database.Cursor
  2. cursor.getString()/cursor.getColumnIndex() 

鸿蒙:

  1. ohos.data.resultset 

※数据结构

1.应用程序数据共享

安卓:

  1. context.getContentResolver(); 
  2. resolver.getType(uri) 

鸿蒙:

  1. ohos.aafwk.ability.DataAbilityHelper 

2.JSON解析

安卓:

  1. import org.json.JSONArray; 
  2. import org.json.JSONException; 
  3. import org.json.JSONObject; 
  4. import org.json.JSONTokener; 

鸿蒙:

  1. Gson,fastJson 

3.对象序列化

安卓:

  1. android.os.Parcel; 
  2. parcel.readParcelable();parcel.writeParcelable() 

鸿蒙:

  1. ohos.utils.parcel 

4.浮点数矩形,获取中心点

安卓:

  1. RectF.centerX() 

鸿蒙:

  1. RectFloat.getCenter().getPointX() 

5.数据结构类

安卓:

  1. LongSparseArray 
  2. SparseArrayCompat 

鸿蒙:

使用HashMap

备注:

内存使用和查找性能会有影响。"

6.浮点数矩形

安卓:

  1. RectF 

鸿蒙:

  1. RectFloat 

7.浮点坐标

安卓:

  1. PointF 

鸿蒙:

  1. 可使用Point 

※对话框

1.对话框销毁

安卓:

  1. mDialog.dismiss() 

鸿蒙:

  1. mDialog.destroy(); 

2.对话框中加载布局

安卓:

  1. mDialog.setContentView(ViewGroup dialogView) 

鸿蒙:

  1. setContentCustomComponent(Componnet comp) 

3.点击对话框外部关闭对话框

安卓:

  1. mDialog.setCancelable(mPickerOptions.cancelable) 

鸿蒙:

  1. mDialog.setDialogListener(new BaseDialog.DialogListener() { 
  2.                @Override 
  3.                public boolean isTouchOutside() { 
  4.                    mDialog.destroy();                dialogView.getComponentParent().removeComponent(dialogView); 
  5.                    return true
  6.                } 
  7.            }); 

备注:

鸿蒙对话框销毁之后需移除对话框中加载的布局,否则再次加载会报错"

※动画

1.旋转动画

安卓:

  1. android.view.animation.RotateAnimation 

鸿蒙:

  1. ohos.agp.animation.AnimatorProperty 

2.值动画及相关回调

安卓:

  1. android.animation.ValueAnimator 
  2. ValueAnimator.AnimatorUpdateListener 
  3. Animator.AnimatorListener 
  4. Animator.AnimatorPauseListener 

鸿蒙:

  1. ohos.agp.animation.AnimatorValue 
  2. AnimatorValue.ValueUpdateListener 
  3. Animator.StateChangedListener 
  4. Animator.LoopedListener 

备注:

启动动画时,AnimatorValue必须作为类的成员变量,而不能时函数局部变量,否则动画不会启动"

3.线性插值器

安卓:

  1. LinearInterpolator 

鸿蒙:

自己写一个

  1. public interface Interpolator { 
  2.     float getInterpolation(float input); 
  3. public class LinearInterpolator implements Interpolator { 
  4.     public LinearInterpolator() { 
  5.     } 
  6.     public LinearInterpolator(Context context, AttrSet attrs) { 
  7.     } 
  8.     public float getInterpolation(float input) { 
  9.         return input; 
  10.     } 

4.设置动画循环次数

安卓:

  1. animation.setRepeatCount(Animation.INFINITE) 

鸿蒙:

  1. animator.setLoopedCount(Animator.INFINITE) 

※存储

获取存储根路径

安卓:

  1. Environment.getExternalStorageDirectory().getAbsolutePath(); 

鸿蒙:

  1. System.getProperty("user.dir"

※Canvas绘图

1.绘制圆弧

安卓:

  1. Android canvas.drawArc() 

鸿蒙:

  1. ohos.agp.render; class Arc 

2.绘制圆形的两种方式

安卓:

  1. canvas.drawCircle(float x, float y, float radius, Paint paint) 

鸿蒙:

  1. A.canvas.drawPixelMapHolderRoundRectShape(PixelMapHolder holder, RectFloat rectSrc, RectFloat rectDst, float radiusX, float radiusY) 
  2.  
  3. B.canvas.drawCircle(float x, float y, float radius, Paint paint) 

3.绘制文本的方法

安卓:

  1. drawText (String text, float x, float y, Paint paint) 

鸿蒙:

  1. drawText(Paint paint, String text, float x, float y) 

4.获取text 的宽度

安卓:

  1. text.getWidth(); 

鸿蒙:

  1. Paint paint = new Paint(); 
  2. paint.setTextSize(text.getTextSize()); 
  3. float childWidth = paint.measureText(text.getText()); 

欢迎交流:HWIS-HOS@isoftstone.com

想了解更多内容,请访问:

51CTO和华为官方战略合作共建的鸿蒙技术社区

https://harmonyos.51cto.com


本文转载自网络,原文链接:https://harmonyos.51cto.com/#zz
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:Web开发应了解的5种设计模式 下一篇:没有了

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐