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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How do I handle local storage in uni-app? How do I handle local storage in uni-app? Mar 11, 2025 pm 07:12 PM

This article details uni-app's local storage APIs (uni.setStorageSync(), uni.getStorageSync(), and their async counterparts), emphasizing best practices like using descriptive keys, limiting data size, and handling JSON parsing. It stresses that lo

How to rename UniApp download files How to rename UniApp download files Mar 04, 2025 pm 03:43 PM

This article details workarounds for renaming downloaded files in UniApp, lacking direct API support. Android/iOS require native plugins for post-download renaming, while H5 solutions are limited to suggesting filenames. The process involves tempor

How to handle file encoding with UniApp download How to handle file encoding with UniApp download Mar 04, 2025 pm 03:32 PM

This article addresses file encoding issues in UniApp downloads. It emphasizes the importance of server-side Content-Type headers and using JavaScript's TextDecoder for client-side decoding based on these headers. Solutions for common encoding prob

How do I use uni-app's geolocation APIs? How do I use uni-app's geolocation APIs? Mar 11, 2025 pm 07:14 PM

This article details uni-app's geolocation APIs, focusing on uni.getLocation(). It addresses common pitfalls like incorrect coordinate systems (gcj02 vs. wgs84) and permission issues. Improving location accuracy via averaging readings and handling

How do I manage state in uni-app using Vuex or Pinia? How do I manage state in uni-app using Vuex or Pinia? Mar 11, 2025 pm 07:08 PM

This article compares Vuex and Pinia for state management in uni-app. It details their features, implementation, and best practices, highlighting Pinia's simplicity versus Vuex's structure. The choice depends on project complexity, with Pinia suita

How do I make API requests and handle data in uni-app? How do I make API requests and handle data in uni-app? Mar 11, 2025 pm 07:09 PM

This article details making and securing API requests within uni-app using uni.request or Axios. It covers handling JSON responses, best security practices (HTTPS, authentication, input validation), troubleshooting failures (network issues, CORS, s

How do I use uni-app's social sharing APIs? How do I use uni-app's social sharing APIs? Mar 13, 2025 pm 06:30 PM

The article details how to integrate social sharing into uni-app projects using uni.share API, covering setup, configuration, and testing across platforms like WeChat and Weibo.

How do I use uni-app's easycom feature for automatic component registration? How do I use uni-app's easycom feature for automatic component registration? Mar 11, 2025 pm 07:11 PM

This article explains uni-app's easycom feature, automating component registration. It details configuration, including autoscan and custom component mapping, highlighting benefits like reduced boilerplate, improved speed, and enhanced readability.

See all articles