我有一个 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 上的通知,但我真正需要的是防止此类代码使用如此多的内存。
更新:
答案建议我应该关闭流、扫描仪等,我不确定这是否有必要(关闭流和扫描仪并不能解决问题),但我认为这不是问题,因为无论如何它们都被成功删除了。
问题是它们在被删除之前堆积起来,我想在线程 hibernate 之前删除它们,而不是等待垃圾收集器,而且据我所知,这在 Java 中无法完成,我需要一种更“垃圾收集器友好”的方法。
最佳答案
在finally block 中你可以做以下事情
finally {
try {
freeOut.close();
} catch (IOException e) {
e.printStackTrace();
}
关于java - 安卓和Java : Reduce memory usage on a service loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143667/