通过ADB多次访问应用程序数据库而不关闭连接?

时间:2016-05-03 12:55:20

标签: java android sqlite adb

我正在使用ADB访问这样的应用程序数据库: public static int runCommandInt(String arg1){     尝试{             ProcessBuilder proc = new ProcessBuilder(adbLocation,“shell”,“sqlite3”,                 “/data/data/com.package/databases/Database.db”,arg1);             过程p = proc.start();             BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));             BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));             String s = null;             int i = 0;             while((s = stdInput.readLine())!= null){                 i = Integer.parseInt(s);                 p.destroyForcibly();                 回归我;             }             while((s = stdError.readLine())!= null){                 的System.out.println(一个或多个);             }         } catch(例外e){             e.printStackTrace();         }         返回0; } 然而,问题是,每次我尝试运行命令时,它都会打开和关闭adb(因此也是数据库连接 - 效率极低),有没有办法获得相同的adb窗口并执行那里有更多命令? 不幸的是,它必须通过adb。每秒拉一次数据库并在本地检查会留下太多的错误空间。

2 个答案:

答案 0 :(得分:0)

创建启动重定向标准输入和标准错误的命令提示符的进程

然后将命令写入标准输入,如下所示

p.standardinput.writeline(" adb命令到这里"); 当命令完成或使用异步读取标准错误或输出以获取您返回的信息时

答案 1 :(得分:-1)

是的,好问题!查看ConnectionManager的此代码!它使用所谓的Singleton模式,其中ConstructionManager对象的唯一构造函数是private。您使用getInstance方法来获取数据库连接的实例。如果已存在连接实例,则只返回已存在的Connection。否则,它继续并构建一个新的。这样,你只需要第一次连接。

public class ConnectionManager {
    private static ConnectionManager instance = null;

    private final String USERNAME = "corbin";
    private final String PASSWORD = "letmein";
    private final String CONNECTION = "jdbc:hsqldb:file:C:\\Users\\Corbin\\Java Proj\\TaskTracker\\Kurafuto\\db";

    private Connection conn = null;

    private ConnectionManager() {
    }

    public static ConnectionManager getInstance() {
        if (instance == null) {
        instance = new ConnectionManager();
        }
        return instance;
    }

    private boolean openConnection() {
        try {
        conn = DriverManager.getConnection(CONNECTION, USERNAME, PASSWORD);
        System.out.println("Connection Opened!");
        return true;
        } catch (SQLException e) {
        System.err.println(e);
        return false;
        }
    }

    public Connection getConnection() {
        if (conn == null) {
        if (openConnection()) {
            return conn;
        } else {
            return null;
        }
        }
        return conn;
    }

    public void close() {
       System.out.println("Closing connection...");
        try {
        conn.close();
        conn = null;
        } catch (Exception e) {
        }
    }
}

使用Connection

获取ConnectionManager.getInstance().getConnection();