软件工程日报——安卓stuio自动检索数据库

发布时间 2023-05-27 23:56:14作者: 伽澄

今天进行整合时,发现安卓端的自动检索数据库进行弹窗的功能还没没有进行解决

以下是在网上找到的思路

创建一个名为DatabaseChecker的线程,在其中实现与MySQL数据库的连接、执行检索代码、比较数据变化、推送通知窗口等功能。在该线程的run()方法中,将会不断执行定时检索代码。

public class DatabaseChecker extends Thread {
    private Context context;
    private boolean running = false;
    private Timer timer;

    public DatabaseChecker(Context context) {
        this.context = context.getApplicationContext();
    }

    public synchronized void startChecking() {
        if (!running) {
            running = true;
            timer = new Timer();
            timer.schedule(new MyTimerTask(), 0, 10000);
        }
    }

    @Override
    public synchronized void run() {
        while (running) {
            // 执行数据库检索代码
            checkDataUpdate();
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void stopChecking() {
        if (running) {
            running = false;
            timer.cancel();
        }
    }

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            // 执行数据库检索代码
            checkDataUpdate();
        }
    }

    private void checkDataUpdate() {
        // 执行MySQL查询代码
        ResultSet newResult = queryDataFromMysql();
        if (newResult == null) {
            return;
        }
        if (oldResult == null) {
            oldResult = newResult;
            return;
        }
        try {
            if (!oldResult.next() && !newResult.next()) {
                return;
            }
            if (oldResult.next() != newResult.next()) {
                // 数据库数据发生变化,推送弹窗
                NotificationCompat.Builder builder =
                        new NotificationCompat.Builder(context, "channel_id")
                                .setSmallIcon(R.drawable.ic_notification)
                                .setContentTitle("数据更新提示")
                                .setContentText("数据库中的数据已更新")
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

                NotificationManagerCompat notificationManager =
                        NotificationManagerCompat.from(context);

                // notificationId是应用程序中的通知唯一标识符
                notificationManager.notify(notificationId, builder.build());
            }
            oldResult = newResult;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

DatabaseChecker类中,queryDataFromMysql()方法的实现可以参考下面的步骤。

  1. 在主界面中启动检索线程

在 MainActivity 的 onCreate() 方法中启动 DatabaseChecker线程,如下所示:

public class MainActivity extends AppCompatActivity {
    private DatabaseChecker databaseChecker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseChecker = new DatabaseChecker(this);
        databaseChecker.startChecking();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        databaseChecker.stopChecking();
    }
}
  1. 解析数据库检索结果

checkDataUpdate()方法中对检索结果进行解析,将当前和上一次的结果进行比较。在第一次检索时,可以将oldResult字段设为null,以便在后续的检索中不会将第一条记录误判成更新数据。

private ResultSet oldResult;

private ResultSet queryDataFromMysql() {
    ResultSet result = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://MySQL服务器名称:端口号/数据库名称",
                "数据库用户名", "数据库密码");
        String sql = "select * from 数据表名称";
        Statement statement = connection.createStatement();
        result = statement.executeQuery(sql);
        statement.close();
        connection.close();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "连接数据库失败", Toast.LENGTH_SHORT).show();
    }
    return result;