gpt4 book ai didi

java - Android - 让应用程序发送心跳到服务器

转载 作者:可可西里 更新时间:2023-11-01 16:38:15 28 4
gpt4 key购买 nike

我需要实现一个常规的心跳

heartbeat 本身是对我的服务器的简单 HTTP-GET 调用。

只要我的应用程序处于打开状态,我就想发送它。当我关闭应用程序时,发送应该停止。

我读了一些关于 Services 的东西和 AlarmManager但是在浏览我的应用程序 Activity 时如何调用/停止它们?

This also看起来不错,但仍然是同样的问题:

final Handler handler = new Handler();
Runnable runable = new Runnable() {

@Override
public void run() {
try{
//do your code here
//also call the same runnable
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runable, 1000);

有人可以发布一个很好的示例或链接吗?

谢谢!

最佳答案

The thing is I want to send it as long as my app is open. When I close the app the sending should stop

在 Android 中比在 iOS 中更难一些,但让我们开始吧:在 Android 中,当应用程序进入后台或被杀死时,您在应用程序级别没有回调。例如,您应该在每个 Activity onStop 方法中处理而不是细化。看一下 Activity 生命周期: enter image description here

或 onDestroy 方法。笔记:当某个 Activity 不再可见时,可能是因为您的应用已进入后台、已关闭或其他 Activity 可见。您必须决定是哪种情况,并在需要时使用您的 HTTP Get/Post 或停止它。

Here是一个带有异步任务的示例代码,用于通过 HTTP 发送数据。

关于java - Android - 让应用程序发送心跳到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18252560/

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