android service开线程,Android 在Service 中开启线程执行任务,Service占用的内存愈来愈多,怎么回事?...

public class SecondWatchService extends Service {

private ExistThread existThread;

@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();

existThread = new ExistThread();

existThread.start();

}

private class ExistThread extends Thread{

@Override

public void run() {

try {

while(true){

if (!isServiceRunning()) {

System.out.println("该程序已被kill掉");

}

sleep(cycletime);

}

} catch (Exception e) {

System.out.println("异常");

}

}

}

private boolean isServiceRunning() {

ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

for (RunningServiceInfo service : manager

.getRunningServices(Integer.MAX_VALUE)) {

if (“com.lsp.service.MyService”)

.equals(service.service.getClassName())) {

return true;

}

}

return false;

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// TODO Auto-generated method stub

System.out.println("FirstWatchService -> onStartCommand");

Notification n = new Notification(R.drawable.ic_launcher,

"Floats Start!", System.currentTimeMillis());

// 将此通知放到通知栏的"Ongoing"即"正在运行"组中

n.flags |= Notification.FLAG_ONGOING_EVENT;

// 代表在点击了通知栏中的"清除通知"后,此通知不清除,

// 常常与FLAG_ONGOING_EVENT一块儿使用

n.flags |= Notification.FLAG_NO_CLEAR;

// PendingIntent pi = PendingIntent.getActivity(this, 0, new

// Intent(this,MainActivity.class), 0);

PendingIntent pi = PendingIntent.getService(this, 2, new Intent(this,

SecondWatchService.class), 2);

n.contentIntent = pi;

n.setLatestEventInfo(this, "Service", "正在运行!", pi);

this.startForeground(0x5895, n);

return super.onStartCommand(intent, flags, startId);

}

@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

stopForeground(true);

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值