Android 和 Java:减少服务循环上的内存使用

2023-12-01

我有一个 Android 服务,它使用此线程每秒更新一个通知(评论并不真正相关):

thread = new Thread() {
    @Override
    public void run() {
        // Preparando la notificación de Swap
        NotificationCompat.Builder notificationSwap =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(android.R.drawable.ic_dialog_info)
                        .setContentTitle("Notificator:");
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int notificationSwapId = 1; // TODO: Asignar un ID que no sea "Magic number"

        while (!stop) {
            String swapInfo = null;

            try{ // TODO: free devuelve siempre 4 líneas?
                Process free = Runtime.getRuntime().exec("free");
                BufferedReader freeOut =
                        new BufferedReader(
                                new InputStreamReader(new DataInputStream(free.getInputStream())));
                free.waitFor();
                freeOut.readLine();
                freeOut.readLine();
                freeOut.readLine();
                swapInfo = freeOut.readLine();
            }catch(Exception e){
                Log.e("ERROR", e.toString()); // TODO: Mejorar esto
            }
            Scanner scanner = new Scanner(swapInfo); // TODO: Mejorar esto
            String swapInfo2 = null;
            if (scanner.hasNext()) {
                scanner.skip("Swap:");
            }
            if (scanner.hasNextInt()) {
                /*swapInfo2 = "Total: " + */scanner.nextInt();
            }
            if (scanner.hasNextInt()) {
                swapInfo2 = "Usado: " + scanner.nextInt();
            }
            if (scanner.hasNextInt()) {
                swapInfo2 += "\nLibre: " + scanner.nextInt();
            }

            // Notificando
            notificationSwap.setContentText(swapInfo2);
            notificationManager.notify(notificationSwapId, notificationSwap.build());

            // Intentando liberar memoria
            //System.gc();

            try {
                Thread.sleep(new Integer(PreferenceManager.getDefaultSharedPreferences(context).getString("frecuency", "60000"))); // TODO: Mejorar esto
            } catch (InterruptedException e){
                Log.d("Notificator (Service)", "Deteniendo el hilo durante la espera"); // TODO: Mejorar esto
                // TODO: ¿Qué pasa si el hilo es interrumpido fuera del try/catch? Si pilla la interrupción no hace falta la variable stop
            }
        }
    }
};

问题是它使用了大约 20MB 的内存,但如果我取消注释“//System.gc();”该数字下降到大约 3/4MB,那是很多垃圾。但是每个循环运行整个垃圾收集器对我来说似乎效率不高,并且 CPU 使用率会更高。

这就是为什么我不喜欢垃圾收集器,在 C++ 循环中仅使用自动变量就不会出现这个问题,但我认为这可以做得更好,因为我既不习惯 Java 也不习惯 Android。

所以,我的主要问题是,如何以更有效的方式降低内存使用量?我也希望有更好的方法来更新 Android 上的通知,但我真正需要的是防止此类代码使用如此多的内存。

UPDATE:

答案建议我应该关闭流、扫描仪等,我不太确定这是否有必要(关闭流和扫描仪不能解决问题),但我认为这不是问题,因为它们是无论如何都被成功删除了。

问题是它们在被删除之前堆积起来,我想在线程休眠之前删除它们,而不是等待垃圾收集器,而且据我所知,这在 Java 中无法完成,我需要一个更“垃圾收集器”友好”的态度。


在finally块中你可以做以下事情

 finally {
try {
    freeOut.close();
} catch (IOException e) {
    e.printStackTrace();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 和 Java:减少服务循环上的内存使用 的相关文章

随机推荐