简体   繁体   English

获取服务中(失去)连接更改的“回调”

[英]Get a “callback” for (loss of) connectivity change in a Service

Specifics: I have a service that runs the notification cast controls (CastCompanionLibrary). 细节:我有一个运行通知转换控件(CastCompanionLibrary)的服务。 When I lose connection, the cast manager doesn't try to tear down the service quick enough. 当我失去连接时,演员经理不会试图快速拆除服务。 So if the user sleeps the device within a couple seconds of connectivity loss, the notification doesn't get taken down. 因此,如果用户在几秒钟的连接丢失内睡眠设备,则通知不会被取消。

General Question: How can I get a callback/alert of a connectivity change in a Service? 一般问题:如何获得服务中连接更改的回调/警报?

You can programmatically create a BroadcastReceiver in your Service that listens for the ConnectivityManager.CONNECTIVITY_ACTION action, calling registerReceiver() when you want to start listening (say, in onCreate() or when you show the notification you eventually want to hide), then calling unregisterReceiver() when you want to stop listening (such as in onDestroy() or when you remove the notification). 您可以在Service中以编程方式创建一个BroadcastReceiver ,用于侦听ConnectivityManager.CONNECTIVITY_ACTION操作,当您想要开始侦听时调用registerReceiver() (例如,在onCreate()或当您显示最终要隐藏的通知时),然后调用当你想要停止监听时(例如在onDestroy()或当你删除通知时) unregisterReceiver( )。

You can then retrieve the connectivity by using code such as 然后,您可以使用诸如的代码来检索连接

boolean isDisconnected = intent.getBooleanExtra(
            ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

in your onReceive() method. 在你的onReceive()方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM