gpt4 book ai didi

java - 为什么我无法停止 Android 中的服务?

转载 作者:行者123 更新时间:2023-12-01 07:42:28 30 4
gpt4 key购买 nike

Intent helloservice = new Intent(this, HelloService.class);
startService(helloservice);
...
stopService(helloservice);

为什么这不起作用?它只是继续运行。我是否缺少一些绑定(bind)或其他东西?

顺便说一下,这是我的服务:

public class HelloService extends Service {
private Timer timer = new Timer();
private long INTERVAL = 1000;

public void onCreate() {
super.onCreate();
startservice();
}

private void startservice() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
Log.d("service", "This proves that my service works.");
}
}, 0, INTERVAL);
; }

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

最佳答案

要使 Timer 在服务停止时消失,您需要在适当的回调中对 Timer 调用 cancel()服务方法; onDestroy 从外观上看。

Even if I stop my service...my timer runs? Why?

因为,就 Android 操作系统而言,Timer 实例在逻辑上不与任何特定服务相关联。服务实现负责处理释放垃圾收集器无法处理的任何资源。 (打开文件句柄和数据库连接是我想象的其他示例。)

关于java - 为什么我无法停止 Android 中的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2265217/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com