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);
}
}
Android 在Service 中开启线程执行任务,Service占用的内存越来越多,怎么回事?
最新推荐文章于 2021-05-27 02:05:45 发布