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

How uniapp integrates native development

Apr 23, 2023 am 09:19 AM

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 "";
    }
}
Copy after login

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
Copy after login

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"
      }
    }
  }
Copy after login

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
}
Copy after login

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"
  }
Copy after login

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()
        }
    }
}
Copy after login

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)
    }
}
Copy after login

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)
        }
    }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the different types of testing that you can perform in a UniApp application? What are the different types of testing that you can perform in a UniApp application? Mar 27, 2025 pm 04:59 PM

The article discusses various testing types for UniApp applications, including unit, integration, functional, UI/UX, performance, cross-platform, and security testing. It also covers ensuring cross-platform compatibility and recommends tools like Jes

What debugging tools are available for UniApp development? What debugging tools are available for UniApp development? Mar 27, 2025 pm 05:05 PM

The article discusses debugging tools and best practices for UniApp development, focusing on tools like HBuilderX, WeChat Developer Tools, and Chrome DevTools.

How can you reduce the size of your UniApp application package? How can you reduce the size of your UniApp application package? Mar 27, 2025 pm 04:45 PM

The article discusses strategies to reduce UniApp package size, focusing on code optimization, resource management, and techniques like code splitting and lazy loading.

How can you use lazy loading to improve performance? How can you use lazy loading to improve performance? Mar 27, 2025 pm 04:47 PM

Lazy loading defers non-critical resources to improve site performance, reducing load times and data usage. Key practices include prioritizing critical content and using efficient APIs.

How can you optimize images for web performance in UniApp? How can you optimize images for web performance in UniApp? Mar 27, 2025 pm 04:50 PM

The article discusses optimizing images in UniApp for better web performance through compression, responsive design, lazy loading, caching, and using WebP format.

What are some common patterns for managing complex data structures in UniApp? What are some common patterns for managing complex data structures in UniApp? Mar 25, 2025 pm 02:31 PM

The article discusses managing complex data structures in UniApp, focusing on patterns like Singleton, Observer, Factory, and State, and strategies for handling data state changes using Vuex and Vue 3 Composition API.

What are computed properties in UniApp? How are they used? What are computed properties in UniApp? How are they used? Mar 25, 2025 pm 02:23 PM

UniApp's computed properties, derived from Vue.js, enhance development by providing reactive, reusable, and optimized data handling. They automatically update when dependencies change, offering performance benefits and simplifying state management co

How does UniApp handle global configuration and styling? How does UniApp handle global configuration and styling? Mar 25, 2025 pm 02:20 PM

UniApp manages global configuration via manifest.json and styling through app.vue or app.scss, using uni.scss for variables and mixins. Best practices include using SCSS, modular styles, and responsive design.

See all articles