用户刷了最近的app后,如何发起网络请求?看起来android在应用程序进程被终止后不允许网络访问。有没有办法还能做到这一点?
我想要管理用户的在线状态,其中应用程序启动使他在线,当应用程序完全被杀死时,他离线。这是通过向我的API发送请求来完成的。
发布于 2020-03-16 18:33:50
这相当简单。你可以编写一个Android服务组件,它会重写一个名为onTaskRemoved()的方法,该方法会在应用程序从recants中滑动移除时触发。因此,您可以尝试此解决方案,并查看它是否满足您的需求。这将极大地解决你的问题。
发布于 2020-03-16 18:27:25
您可以创建一个监听应用程序销毁的服务
class MyService: Service() {
override onBind(intent:Intent):IBinder {
return null
}
override onStartCommand(intent:Intent, flags:Int, startId:Int):Int {
return START_NOT_STICKY
}
override onDestroy() {
super.onDestroy()
}
override onTaskRemoved(rootIntent:Intent) {
// this will be called when Your when the application is destroyed or killed
// launch your Network request here
}
}并在清单文件中定义此服务:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
...>
...
<application
android:name=".MyApplication">
...
<service android:name=".MyService" android:stopWithTask="false"/>
</application>
</manifest>然后在您的应用程序中启动它
class MyApplication: Application{
override onCreate(){
super.onCreate()
val intent = Intent(this, MyService::java.class)
startService(intent)
}
}检查此thread。
https://stackoverflow.com/questions/60703678
复制相似问题