lcpsky

导航

JavaFX程序自动更新主程序功能开发

查看是否能连接上服务器

  if (UpdateUtil.isOnline("www.baidu.com",1,150)){
            ConfirmWin confirmWin = new ConfirmWin();
            if(ConfirmWin.isOk){
               //如果更新需要结束debug服务
                DevToolsDebuggerServer.stopDebugServer();
                RuntimeUtil.restartApp();
            }else {
                LocalServer.startLocalServer();
            }
        }

Confirm询问框实现

package elements;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;

import java.util.Optional;

/**
 * @author: Administrator
 * @date: 2021/05/11 16:57
 * @description:
 */
public class ConfirmWin {
    public static boolean isOk = false;
    public ConfirmWin(){
        // 创建一个确认对话框
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        // 设置对话框的头部文本
        alert.setHeaderText("提示");
        // 设置对话框的内容文本
        alert.setContentText("发现新版本,是否需要在线更新?");
        // 显示对话框,并等待按钮返回
        Optional<ButtonType> buttonType = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消,再据此分别进一步处理
        // 单击了取消按钮CANCEL_CLOSE
        // 单击了确定按钮OK_DONE
        if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
            isOk = true;
        } else {
            isOk = false;
        }
    }
}

效果
在这里插入图片描述

连接服务器状态测试工具

public class UpdateUtil {

    private static final Pattern PING_PATTERN = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",    Pattern.CASE_INSENSITIVE);

    /**
     * 功能描述: <br>
     * 〈ping命令封装〉
     * @Param: [ipAddress, pingTimes, timeOut]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2021/05/11 10:01
     */
    public static boolean isOnline(String ipAddress,int pingTimes,int timeOut){
        String pingCommand = "ping " + ipAddress + " -n " + pingTimes    + " -w " + timeOut;
        String result = "";
        InputStream inputStream = null;
        Runtime runtime = Runtime.getRuntime();

        try {
            Process exec = runtime.exec(pingCommand);
            if(exec==null){
                return false;
            }
            inputStream = exec.getInputStream();
            result = CommonUtil.getStringFromInputStream(inputStream,Charset.forName("GB2312"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(getCheckResult(result)==1){
            return true;
        }
        return false;
    }


    /**
     * 功能描述: <br>
     * 〈若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.〉
     * @Param: [line]
     * @Return: int
     * @Author: Administrator
     * @Date: 2021/05/11 10:02
     */
    private  static  int getCheckResult(String line) {
        Matcher matcher = PING_PATTERN.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
}

应用重启运行时工具

重启程序使用外部命令行重启,需要创建restart.bat文件,内容为 java -jar javafx-web-app.jar

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RuntimeUtil {


    public static String exec(String command) {
        StringBuilder sb = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            process.getOutputStream().close();
            reader.close();
            process.destroy();
        } catch (Exception e) {
            System.out.println("执行外部命令错误,命令行:" + command+e);
        }
        return sb.toString();
    }

    private static String jps() {
        return exec("jps -l");
    }
    private static String getPid(){
        String name = ManagementFactory.getRuntimeMXBean().getName();
        System.out.println(name);
        return name.split("@")[0];
    }


    public static void restartApp(){
        long period = 1500;
        long initialDelay = 1000;
        String jpsPre = RuntimeUtil.jps();
        System.out.println(jpsPre);
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!jpsPre.equals(RuntimeUtil.jps())){
                    System.out.println("关闭程序");
                    System.exit(0);
                }
            }
        },initialDelay,period, TimeUnit.MILLISECONDS);
        String restartBat = CommonUtil.getFilePath()+ File.separator+"restart.bat";
        String strcmd = "cmd /c start  "+restartBat;
        RuntimeUtil.exec(strcmd);
    }
}

总结
以上已经完成对应用的升级工作,增加了版本升级提示功能。https://gitee.com/lcpsky1991/javafx-web-app.git
后续功能将陆续添加。

posted on 2021-05-12 12:44  lcpsky  阅读(304)  评论(0)    收藏  举报