UTS development application on Android system

uts for Android

This article aims to help Android developers get started with UTS quickly.

Readers are required to have Android native application development experience.

# 1 Understand what the UTS plugin is

UTS插件It is uni-appa new plug-in form, which has the advantages of cross-platform, high efficiency, and easy debugging. Details(opens new window)

For Android developers, what we need to know is:

  1. When compiling: When we save UTSthe source code file, the IDE will synchronously compile it into the corresponding Kotlin code.
  2. Runtime: When the real machine is running/cloud packaging, these compiled kotlin source codes will also become part of the apk

# 2 Master UTS grammar

# 2.1 For those who master the kotlin language

Because the UTS syntax is very similar to kotlin, it is recommended to master the UTS syntax in practice after a quick reading. Introduction to uts syntax (opens new window) .

# 2.2 For those who only master the java language

Compared with js, the syntax of uts is more similar to java. However, there are still big differences, and you need to read the 2.3 grammar section in detail.

Although the development of UTS plug-ins does not require mastering kotlin, but given that it UTSis currently on the android platform, it will be compiled into kotlin source code. Learn the kotlin language to facilitate troubleshooting and implementation of complex functions.

Therefore, it is recommended to learn kotlin syntax.

# 2.3 Data Type Differences

Although UTS and koltin are basically consistent in data types, there are still differences in some scenarios, which are specifically explained here

In principle:

The data type is subject to the built-in type of UTS, and each native platform will automatically adapt to it.

However, UTS itself is a cross-platform language. When the API of a specific platform has clear requirements, the data type clearly required by the other party shall prevail.


#Example 1: Int and Number

By default UTS developers can use  Number overlays for the scenes android used on the platform  Int.

But when the developer rewrites  Service the component onStartCommand method, Android the API requirements clearly require that the last two parameters must be Int

In the native development environment, it should be written like this:

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
   return super.onStartCommand(intent, flags, startId);
}

Copy code

In the standard TS environment, there are only Numbertypes and no Inttypes

In order to adapt to this situation, UTS allows developers to use the data type Int of the native platform to meet the data type requirements of the native API:

 override onStartCommand(intent:Intent ,flags:Int ,startId:Int):Int {
	return super.onStartCommand(intent, flags, startId);
 }

Copy code

#Example 2:MutableList

MutableListIt is androida platform-specific data type. In general scenarios, it can be  Array replaced by the built-in type in UTS

However, when calling onAppActivityRequestPermissionsResult the function to monitor the result of the permission application, it is explicitly required to use this type of parameter

In the native environment, it should be written like this:


onAppActivityRequestPermissionsResult(fun(requestCode: Number, permissions: MutableList<String>, grantResults: MutableList<Number>){
      
});

Copy code

In the standard TS environment, there is no MutableListtype, and the similar data type is Array

In order to adapt to this situation, UTS allows developers to use the data types of the native platform MutableListto meet the data type requirements of the native platform API:

onAppActivityRequestPermissionsResult((requestCode: number,permissions: MutableList<string>,grantResults: MutableList<number>) => {
	
});

Copy code

# 3 Android native environment configuration

For Android projects, in addition to source code, it also involves common issues such as dependencies, resources, and configurations.

This chapter will introduce how to configure these properties in the UTS plug-in development environment

Notice:

  • 1 The example codes in this chapter are taken from the Hello UTS  project address(opens new window)
  • 2 The configuration designed in this chapter can only take effect after customizing the base
  • 3 As of HX 3.6.8, the automatic generation of R files is not yet supported, so the part involved in the generation of R files in this chapter is not yet supported. This is a legacy issue and will be supported in a later release.

# 3.1 Configure AndroidManifest.xml

Take the configuration file in the native-page plug-in in hello UTS as an example:

Example file location in hello uts:

~\uni_modules\uts-nativepage\utssdk\app-android\AndroidManifest.xml

AndroidManifest.xml example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 
  // 配置包名
  package="io.dcloud.uni_modules.uts_nativepage">
   // 配置权限
   <!--创建前台服务权限-->
   <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application>
	   // 配置service / activity
	   <service android:name="uts.sdk.modules.utsNativepage.ForeService"  />
       <activity android:name="uts.sdk.modules.utsNativepage.DemoActivity"></activity>
    </application>
</manifest>

Copy code

AndroidManifest.xml configuration rules are consistent with those in android.

Special Note:

Each UTS plugin corresponds to a lib module in the android project.

Unlike you manually enter the package name in android studio, if you do not have a manual package name, HX will generate one by default according to the following rules:

uts插件默认包名规则:

如果是根目录utssdk下的uts插件
	包名:uts.sdk.(插件ID转驼峰)
如果是uni_modules目录下的uts插件
	包名:uts.sdk.modules.(插件ID转驼峰)


举例:
uni-getbatteryinfo -> uts.sdk.modules.uniGetbatteryinfo;
uts-nativepage  ->  uts.sdk.modules.utsNativepage

Copy code

# 3.2 Configure res resources

Example file location in hello uts:

~\uni_modules\uts-nativepage\utssdk\app-android\res

In addition to the layout and values ​​directories listed here, it also supports all android standard resource directories such as anim

# 3.3 Configure asset resources

Take the uts-advance plugin in hello UTS as an example.

key code:

// 获取asset管理器
let assetManager = getAppContext()!.getAssets();
// 加载free.mp3 资源
let afd = assetManager.openFd("free.mp3");
// 使用android 自带的媒体组件进行播放
let mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();

Copy code

The location of the complete code in hello uts:

~\uni_modules\uts-advance\utssdk\app-android\assets

# 3.4 Add libs dependent resources

Take the uts-tencentgeolocation plugin under the Hello UTS project as an example

Example file location in hello uts:

~\uni_modules\uts-tencentgeolocation\utssdk\app-android\libs


The HX3.6.7 version has the following built-in dependencies

Developers need to pay attention to two points when using the dependencies in the list:

  • When the real machine is running, you can directly reference related classes without adding dependencies in the list
  • Do not introduce the same dependencies by adding jar/aar manually, otherwise cloud packaging will fail due to dependency conflicts.
+--- my-imageloader.jar
+--- my-nineoldandroids-2.4.0.jar
+--- zip4j-2.8.0.jar
+--- uts-runtime-jvm-1.0.jar
+--- [email protected]
+--- msa_mdid_1.0.13.aar
+--- breakpad-build-release.aar
+--- androidx.multidex:multidex:2.0.0@aar
+--- androidx.recyclerview:recyclerview:1.0.0@aar
+--- androidx.legacy:legacy-support-v4:1.0.0@aar
+--- androidx.appcompat:appcompat:1.0.0@aar
+--- com.github.bumptech.glide:glide:4.9.0@aar
+--- com.alibaba:fastjson:1.1.46.android@jar
+--- androidx.fragment:fragment:1.0.0@aar
+--- androidx.vectordrawable:vectordrawable-animated:1.0.0@aar
+--- androidx.legacy:legacy-support-core-ui:1.0.0@aar
+--- androidx.media:media:1.0.0@aar
+--- androidx.legacy:legacy-support-core-utils:1.0.0@aar
+--- androidx.vectordrawable:vectordrawable:1.0.0@aar
+--- androidx.viewpager:viewpager:1.0.0@aar
+--- androidx.coordinatorlayout:coordinatorlayout:1.0.0@aar
+--- androidx.drawerlayout:drawerlayout:1.0.0@aar
+--- androidx.slidingpanelayout:slidingpanelayout:1.0.0@aar
+--- androidx.customview:customview:1.0.0@aar
+--- androidx.swiperefreshlayout:swiperefreshlayout:1.0.0@aar
+--- androidx.asynclayoutinflater:asynclayoutinflater:1.0.0@aar
+--- androidx.loader:loader:1.0.0@aar
+--- androidx.core:core:1.0.0@aar
+--- androidx.versionedparcelable:versionedparcelable:1.0.0@aar
+--- androidx.collection:collection:1.0.0@jar
+--- androidx.cursoradapter:cursoradapter:1.0.0@aar
+--- com.github.bumptech.glide:gifdecoder:4.9.0@aar
+--- androidx.lifecycle:lifecycle-runtime:2.0.0@aar
+--- androidx.interpolator:interpolator:1.0.0@aar
+--- androidx.documentfile:documentfile:1.0.0@aar
+--- androidx.localbroadcastmanager:localbroadcastmanager:1.0.0@aar
+--- androidx.print:print:1.0.0@aar
+--- androidx.lifecycle:lifecycle-viewmodel:2.0.0@aar
+--- androidx.lifecycle:lifecycle-livedata:2.0.0@aar
+--- androidx.lifecycle:lifecycle-livedata-core:2.0.0@aar
+--- androidx.lifecycle:lifecycle-common:2.0.0@jar
+--- androidx.arch.core:core-runtime:2.0.0@aar
+--- androidx.arch.core:core-common:2.0.0@jar
+--- androidx.annotation:annotation:1.0.0@jar
+--- com.github.bumptech.glide:disklrucache:4.9.0@jar
\--- com.github.bumptech.glide:annotations:4.9.0@jar


Copy code

# 4 Key differences between Kotlin and UTS (continuously updated)

Read through the chapters above.

So far we think that you have mastered UTS syntax, basic Kotlin syntax, and UTS support for android resources.

But for a kotlin language user who is familiar with android development, there are many common habits that have changed. We will specifically point out in this chapter, so that developers can deepen their understanding.

# 4.1 Syntax differences


# 4.1.1 Nullable syntax flags

In kotlin, the nullable syntax is unified as a type and then added ?. Take the following code as an example

// 一个可为空的字符串变量,变量名为user
var user:String? = null

Copy code

But there are two cases in ts, if it is a global variable, it can be empty, you need to write like this

let user:string | null

Copy code

If it is a member variable, it is similar to kotlin, but the difference is that ? is written after the variable, not after the type

let user?:string

Copy code

# 4.1.2 let and var

kotlinThe variable variable in is modified as  var, val. The difference is that val is immutable and var is mutable.

utsvarThe corresponding variable type  invar/let

It is recommended to use let because it will only take effect within the scope, and it needs to be used with caution varbecause it has a larger scope of action

# 4.1.3 Method definition

kotlinThere is only one way to define a method in a method definition 

 fun startListener():void{
	 
 }

Copy code

In uts, it is necessary to distinguish between global methods and member methods

 // 成员方法
 startListener():void{
	 
 }

Copy code

 // 全局方法
 function startListener():void{
	 
 }

Copy code

#4.1.4 extends

kotlinIn: Inheritance operator, needs to be extendsreplaced with

grammar kotlin uts
inheritance class : extends
implement the interface : extends
class MediaContentObserver : ContentObserver {
}

Copy code

class MediaContentObserver extends ContentObserver {
}

Copy code

# 4.1.5 Non-null assertion

The non-null assertion in kotlin is !!, in ts is a!

user!.sayHello();

Copy code

user!!.sayHello();

Copy code

# 4.1.6 Quickly call the parent class implementation

//ts 中快速实现super
constructor() : super() {
}
	

Copy code

//kotlin 中快速实现super
constructor (){
	super();
}

Copy code

# 4.1.7 Anonymous inner class

kotlinAnonymous inner classes can be used in

// kotlin 新建事件监听
user.setListener(Listener(){
	//todo
});

Copy code

The current version of UTS does not support anonymous inner classes, and requires explicit declarations to create new ones

// 声明一个新的类,实现Listener
class MyListener extends Listener{
	// todo
}
// 新建实例
let myListener = new MyListener();
user.setListener(myListener);

Copy code

# 4.1.8 Can be called by empty function

There is a special scenario where we need to define some nullable function variables, such as success and fail below:

type Option = {
	success?: (res: object) => void;
	fail?: (res: object) => void;
};

Copy code

At this time we need to call like this

options.success?.(res)

Copy code

Such a calling method is illegal in kotlin and belongs to the unique syntax in TS, which requires special attention.


# 4.2 Warning Optimization

The following will not affect functional usage, but in a UTS environment, there are suitable solutions

# 4.2.1 Introduction of java lang package

kotlin Or java java.lang.* is specially treated and can be used directly without importing.

// 获取当前时间戳
System.currentTimeMillis()

Copy code

In the UTS environment, the lang package is not treated specially and needs to be imported manually.

// 手动引入lang包下的类
import System from 'java.lang.System';

// 获取当前时间戳
System.currentTimeMillis()

Copy code

# 4.2.2  UTS Shortcut construction is not recommended

kotlin Supports the method of () to quickly realize the declaration of the no-argument constructor

// 获取当前时间戳
class ScreenReceiver extends BroadcastReceiver(){
  
}

Copy code

In the UTS environment, it is not recommended to do this (although it will not affect compilation at present), it is recommended to use manual declaration of no-argument construction

class ScreenReceiver extends BroadcastReceiver{
	
	constructor (){
		super();
	}

}

Copy code

# The variables prefixed with an underscore in 4.2.3  UTS have the meaning of shielding unused warnings

// IDE会提示 name,status,desc 变量未使用
onStatusUpdate(name:string, status:Int, desc:string){
	
}

// 不会警告变量未使用
onStatusUpdate(_name:string, _status:Int, _desc:string){
	
}

Copy code

# 5 Frequently Asked Questions (continuously updated)

# 5.1 How to create a new one in the UTS environment activity?

Refer to the uts-nativepage plugin in the Hello UTS project

path:

~\uni_modules\uts-nativepage

# 5.2 How to create a new one in the UTS environment service?

Refer to the uts-nativepage plugin in the Hello UTS project

path:

~\uni_modules\uts-nativepage

Guess you like

Origin blog.csdn.net/std7879/article/details/127672569