android 循环服务,Android和Java:减少服务循环中的内存使用量

我有一个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 += "

Libre: " + 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上更新通知的更好的方法,但我真正需要的是防止这种代码使用过多的内存.

更新:

答案表明我应该关闭流,扫描仪等,但我不确定这是否必要(关闭流和扫描仪无法解决问题),但我认为这不是问题,因为它们是被成功删除.

问题是它们在被删除之前就堆积了,我想在线程休眠之前而不是等待垃圾收集器之前将它们删除,而且据我所知,在Java中无法做到这一点,因此我需要一个更多的“垃圾收集器”友好”的方式.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值