Cordova 后台运行 Android APP

Github: https://github.com/katzer/cordova-plugin-background-mode

Installation

项目根目录安装

cordova plugin add cordova-plugin-background-mode

Usage

如: 在 Vue 项目中的主页(Home.vue)设置返回键,点击返回后 APP 自动后台运行

  1. 在 Home.vue created() 中设置回退按钮监听事件 (https://cordova.apache.org/docs/en/9.x/cordova/events/events.html#backbutton)
  created () {
    document.addEventListener("backbutton", this.onBackKeyDown, false)
    document.addEventListener('deviceready', function () {
      // cordova.plugins.backgroundMode is now available
    }, false)
  },
  1. 设置 onBackKeyDown() 函数, 点两次返回键退出APP, 在 exitApp() 函数中设置APP后台运行
  methods: {
    onBackKeyDown () {
      console.log('backkeydown')
      document.removeEventListener("backbutton", this.onBackKeyDown, false)
      document.addEventListener("backbutton", this.exitApp, false)
    },
    exitApp () {
      console.log('exit app')
      // navigator.app.exitApp() // 退出APP
      window.cordova.plugins.backgroundMode.moveToBackground() // 后台运行APP
    }    
  }

Version

cordova package.json

"cordova-android": "8.1.0",
"cordova-plugin-background-mode": "^0.7.3",
"cordova-plugin-device": "^2.0.3",

vue package.json

"vue": "^2.6.10",
"@vue/cli-plugin-babel": "^3.11.0",
"@vue/cli-plugin-eslint": "^3.11.0",
"@vue/cli-plugin-pwa": "^3.11.0",
"@vue/cli-service": "^3.11.0",

你可能感兴趣的:(Cordova 后台运行 Android APP)