As a developer who often deals with Android, apK installation is a very frequent thing, but I have no choice but to find a simple PC application that can be used as the default opening mode of APK, and then directly installed to the selected Android device. Create your own PC app.

(Source code and final effect attached at the end of the article)

Requirement design:
  1. It can be used as the default opening mode of APK files.
  2. Enumerates available Android devices that are currently connected to your computer;
  3. Installation status display;
  4. .
Feasibility analysis:

The main function is to transfer apK to the phone and command the phone to install the file. From an Android development point of view, ADB can do this. It provides a series of commands to enable data interaction between PC and phone.

Combined with the above analysis, you can have a rough idea of the product prototype.

Technical research:

For PC application development, of course, PC application development uses the popular ELECTRON, which provides a friendly operating environment and low learning cost, and can meet the needs of most PC application development.

Development and debugging:
  1. The electron application project structure is based on NodeJS. Here [email protected] is used to initialize the project:
NPM init NPM install --save-dev [email protected]Copy the code

Here you can refer to the tutorial on the official website

  1. The next step is to write the business logic,See the source code link at the bottom for details, the main functions are introduced here.
  • Check the operating environment of the software:

The computer will not run without adb environment variable configuration

/** * Check if there is an ADB environment */
async function chcekAdbEnv() {
    const { error, stdout, stderr } = await execPromisefy('adb version');
    if (error) {
        console.error('listDevices|error:', error);
        throw e;
    }
    if (stderr) {
        console.error('listDevices|stderr:', stderr);
        throw e;
    }
    return stdout;
}
Copy the code
  • Enumerating device information:

This function outputs the current array of device ids

/** * enumerates currently connected Android devices */
async function listDevices() {
    console.log('start list devices')
    const { error, stdout, stderr } = await execPromisefy('adb devices');
    if (error) {
        console.error('listDevices|error:', error);
        throw e;
    }
    if (stderr) {
        console.error('listDevices|stderr:', stderr);
        throw e;
    }
    console.log('stdout:', stdout);
    let deviceArray = []
    stdout.split('\n').forEach(line= > {
        if ((line = line.trim()) && line.indexOf('List of devices attached') < 0) {
            deviceArray.push(line.split('	') [0])}})console.log('deviceArray', deviceArray)
    return deviceArray;
}

Copy the code
  • Install APK to the specified device

Enter an ID and print a Promise with a timeout feature

/** * Install APK to specified device * Timeout period defaults to 50s *@param {*} deviceId 
 * @param {*} apkPath 
 */
function installApk(deviceId, apkPath) {
    const installPromise = new Promise(async (resolve, reject) => {
        try {
            const { error, stdout, stderr } = await execPromisefy(`adb -s ${deviceId} install ${apkPath}`);
            if (error) {
                console.error('listDevices|error:', error);
                reject(e);
            }
            if (stderr) {
                console.error('listDevices|stderr:', stderr);
                reject(stderr);
            }
            resolve(stdout)
        } catch (e) {
            console.error(e) reject(e); }})const timeoutPromise = new Promise((resolve, reject) = > {
        setTimeout(() = > { reject('timeout')},50000)})return Promise.race([installPromise, timeoutPromise]);
}
Copy the code
  • The next step is UI drawing and business docking.

This is a simple UI

/ / to omit...
Copy the code
  1. The next step is to output the PC installation package

The electron Builder is used to construct the PC installation package.

At this stage of development, I was puzzled by a problem: how to set my PC application based on electron to the default opening mode of some files?

As a “fake” PC application developer, some of the native API operations are almost utterly ignorant, and if this problem can not be solved, then the app is meaningless, can not be set to open by default, talking about convenience.

After some investigation, it is found that other electron applications such as UTools, Vscode, etc., can be set as the default application, indicating that this path is available.

Finally, I found my way on StackOverflow, and it looks like this:

How do I make my Electron app the default for opening files?

The keyword fileAssociations can be configured in the electron-build configuration to associate your application with files of related suffix types, so you can set it to the default opening mode of related files.

This configuration is described in electron-build:

www.electron.build/configurati…

This section only describes how to configure the file and does not describe how to obtain file information.

After some searching, the road finally opened up:

example-electron-file-association

Key functions:

// Attempt to bind file opening #2
app.on('will-finish-launching'.() = > {
  // Event fired When someone drags files onto the icon while your app is running
  app.on("open-file".(event, file) = > {
    if (app.isReady() === false) {
      initOpenFileQueue.push(file);
    } else {
      windows.create(file);
    };
    event.preventDefault();
  });
});
Copy the code

Yes, the original way to get the file path, but this is for MAC, how to get Windows?

Check out the electron official documentation for an open-file event:

Events’ open – the file ‘macos

Here is the final answer. On Windows, get the path through process.argv.

At this point, all logic comb through, development is done.

Final effect:

Defects and plans:

The biggest flaw at the moment is of course the issue of the size of the installation file after packaging, as Electron knows… If there is still time, I will try to use mini-electron and add the configuration associated with the id and the actual device name (I can’t tell which device ID is at present).

The complete code

I think I can give you a star! thanks

electron-apk-installer

The installation package

The size of the electron bag is a real injury

apk-installer.exe