Home >Web Front-end >uni-app >How uniapp integrates native development

How uniapp integrates native development

PHPz
PHPzOriginal
2023-04-23 09:19:083185browse

With the continuous development of the mobile application market, developing cross-platform applications has also become a trend. As one of the most widely used cross-platform frameworks on the market, Uniapp is loved by developers for its good compatibility, high development efficiency, and simple use. However, when some needs are more customized or some native functions need to be called, using pure Uniapp to develop applications may not be able to meet the needs. At this time, we need to use Uniapp and native for mixed development, which can not only meet some customized needs, but also make full use of the efficiency of Uniapp development. Below we will introduce in detail how Uniapp integrates native development based on actual development experience.

1. Preliminary preparations

Before starting to integrate native development, we need to ensure that the local Android and iOS development environments have been configured and are proficient in using them. At the same time, you also need to ensure that you are familiar with using the Uniapp framework and master basic development operations.

2. Introducing native plug-ins

In Uniapp development, we can use native functions by introducing native plug-ins. There are two ways to introduce native plug-ins in Uniapp, namely developing plug-ins yourself and using plug-ins on the market.

  1. Develop your own plug-ins

It is not difficult to develop native plug-ins. You can write code according to various native development documents. Here I will introduce you to a more general example: obtaining device information.

In Android, we can get the device information through the following code:

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class DeviceInfoUtil {

    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
}

And in iOS, we can get the device information through the following code:

#import <UIKit/UIKit.h>

@interface DeviceInfoUtil : NSObject

+ (NSString *)getUUID;

@end

@implementation DeviceInfoUtil

+ (NSString *)getUUID {
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return uuid;
}

@end

After writing After the native function is created, we need to package it into a plug-in and publish it to the Uniapp market. Next, you can introduce the native plug-in into Uniapp and use it. The specific operations are as follows:

(1) First add a reference to the native plug-in in the manifest.json file in the application project:

"app-plus": {
    // 其他配置
    "plugins": {
      "device": {
        "version": "1.0.0",
        "provider": "xx"
      }
    }
  }

Among them, device is the plug-in name, version is the plug-in version, and provider For plug-in providers.

(2) Use Vue.js syntax to define a JS file, call the plug-in function in the file and export:

const device = uni.requireNativePlugin('device')

function getVersionName() {
    return device.getVersionName()
}

export default {
    getVersionName
}

Among them, uni.requireNativePlugin('device') is the reference plug-in syntax, getVersionName() is the function we defined in the plug-in to get the version number.

2. Use plug-ins on the market

In addition to developing plug-ins ourselves, we can also download native plug-ins developed by other developers on the Uniapp market to use the required native functions . The specific operations are as follows:

(1) Add a custom component containing the required plug-in to the manifest.json file in the application project:

"usingComponents": {
    "xxx": "@/components/xxx/xxx"
  }

where, xxx represents the required native plug-in name , @/components/xxx/xxx indicates the relative path where the plug-in file is located in the project.

(2) Write the code to use the plug-in in the JS file of Vue.js syntax:

import xxx from '@/components/xxx/xxx'

export default {
    data() {
        return {
            versionName: ''
        }
    },
    methods: {
        getVersion() {
            this.versionName = xxx.getVersionName()
        }
    }
}

where, xxx is the name of the plug-in, defined in the methods object of Vue.js syntax The function getVersion() to obtain the plug-in version number is used, and the plug-in method xxx.getVersionName() is called in it to obtain the version number.

3. Native interaction with Uniapp

In the previous steps, we have successfully integrated the native plug-in. However, during development we may also need to implement interaction between native and Uniapp. For example, when users respond to native controls, they need to switch to the Uniapp page; or when the Uniapp page needs to call native functions, they need to call native code, etc. At this time, we need to use the API provided by Uniapp to achieve it.

  1. Call native code

To call native code in Uniapp, you can use the following code:

if (uni.os.android) {
    // Android端
    let intent = new Intent(Intent.ACTION_VIEW)
    intent.setClassName("com.package.name", "com.package.name.MainActivity")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    uni.context.startActivity(intent)
} else if (uni.os.ios) {
    // iOS端
    try {
        window.webkit.messageHandlers.nativeMethod.postMessage(params)
    } catch (e) {
        console.log(e)
    }
}

Among them, the calling method on the Android side needs to use the Android API Intent class, set its jump target and the parameters that need to be transmitted; when calling on the iOS side, you need to first determine whether the messageHandlers attribute exists, and then send the message to the native through the postMessage method, and the parameters need to be converted into JSON format.

  1. Receive native messages

When we need to transfer data from native to Uniapp, we need to define the corresponding callback function in Uniapp in advance so that native can call the function and pass the data. A common function nativeCallback needs to be defined in the Vue.js syntax file to receive native data and process it accordingly in the application.

The following is the code to define the function:

export default {
    data() {
        return {
            versionName: ''
        }
    },
    mounted() {
        // 定义原生回调函数
        window.nativeCallback = (data) => {
            console.log(data)
        }
    }
}

Among them, window.nativeCallback is the name of the defined callback function, and data is the data passed from the native. In the mounted function, we can define the callback function as a global function and then use it wherever we need to receive data.

Through the above methods, we can use native plug-ins and call native code in Uniapp to meet the needs of different scenarios.

4. Summary

This article introduces in detail the steps for Uniapp to integrate native development, and how to use native functions such as native plug-ins and dialog boxes. For developers who need to use some more customized functions or need to quickly develop applications, they can use different native plug-ins or APIs according to actual needs to meet their needs. At the same time, when developing native plug-ins, it is recommended to refer to various native development documents to better master relevant knowledge.

The above is the detailed content of How uniapp integrates native development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn