2020-11-16 cordova配置开机自启动

场景: vue写的H5网页, cordova把它打包成Android的APK, 现在要给它配置开机自启动功能

1. 给config.xml增加

原本的config.xml



    xx
    
        xxx有限公司提供技术支持
    
    
        xxx Team
    
    
    
    
    
    
    
    
    
    
    
      

      
        
      
    
    
        
        
    

参考这个: https://stackoverflow.com/questions/1056570/how-to-auto-start-an-android-application
和这个: https://blog.csdn.net/u012611644/article/details/80542119

$ cat config.xml



    xxx
    
        xxx有限公司提供技术支持
    
    
        xxx Team
    
    
    
    
    
    
    
    
    
    
    
      

      
        
        
      
    
    
        
        
    

PS: 只新增了第30行

2. 给AndroidManifest.xml增加receiver

$ cd platforms/android/app/src/main/
$ cat AndroidManifest.xml



    
    
    
        
            
                
                
            
        
        
            
                
                
            
        
    
    
    
    
    

其中标签(第12-16行)为新增的内容

3. 新建BootUpReceiver.java文件

$ touch BootUpReceiver.java
$ vi BootUpReceiver.java
$ cat BootUpReceiver.java

package io.cordova.hellocordova;

import  android.content.BroadcastReceiver;
import  android.content.Context;
import  android.content.Intent;
import org.apache.cordova.*;

public class BootUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

附: MainActivity.java文件内容(该文件无需修改)
$ cat MainActivity.java

package io.cordova.hellocordova;

import android.os.Bundle;
import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by  in config.xml
        loadUrl(launchUrl);
    }
}
  1. cordova build打包
    $ cd -&&cd ../../../../.. # cd到config.xml所在目录
    $ cordova build
    $ cp platforms/android/app/build/outputs/apk/debug/app-debug.apk ~/auto-startup-xxx.apk
  2. 安装
    直接用U盘把apk拷贝到机器上, 然后双击打开即可

你可能感兴趣的:(2020-11-16 cordova配置开机自启动)