简体   繁体   English

如何在Android中使用后台服务触发wifi状态更改?

[英]How to trigger wifi state change using a background service in android?

I have an application where I want to upload some data as soon as the wifi is turned-on even if the application is not running. 我有一个应用程序,我想在WiFi打开后立即上传一些数据,即使该应用程序未运行也是如此。 I think this can be done using android background services. 我认为可以使用android后台服务来完成。 Please help me uploading the data using background services when the app is not running or suggest me some other way to achieve this. 当应用未运行时,请帮助我使用后台服务上传数据,或者建议我采取其他方法来实现此目的。

Thanks in advance!! 提前致谢!!

To be more eloborate, implement following 为了更加雄辩,请执行以下操作

  • Create a Started service (service which is started using startService() instead of bindService(). 创建一个启动服务(使用startService()而不是bindService()启动的服务。
  • Implement onStartCommand() callback of this service. 实现此服务的onStartCommand()回调。 In this callback method check if there is any data to be uploaded (if this data is created by an activity, it is wise to use a DB table to queue the data to be uploaded and service picks up data from that DB). 在此回调方法中,检查是否有任何要上载的数据(如果此数据是由活动创建的,则明智的做法是使用数据库表对要上载的数据进行排队,然后服务从该数据库中拾取数据)。 Check WIFI connectivity and if available upload the data. 检查WIFI连接,如果可用,请上传数据。
  • Now you need to trigger this service whenever WIFI is available. 现在,只要有WIFI,就需要触发此服务。 Here you 2 ways to imeplemnt 在这里,您有两种方法
  • Method 1 : register in your application manifest file to be notified of WIFI connectivity changes refer this link . 方法1:在您的应用程序清单文件中注册,以通知WIFI连接更改, 请参考此链接 registered broadcast receiver would be called when WIFI state changes. WIFI状态更改时,将调用注册的广播接收器。 from the broadcast receiver start your service if WIFI is available 如果可以使用WIFI,请从广播接收器开始服务
  • Method 2 : using AlarmManager launch you service periodically (say every 10 minutes). 方法2:使用AlarmManager定期启动服务(例如每10分钟启动一次)。 refer this link . 请参阅此链接 This method would be beneficial if data to be uploaded gets generated once in a while. 如果不时生成一次要上传的数据,此方法将非常有用。

Hope this is helpful. 希望这会有所帮助。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。

You must use an unbounded service, who is completely independent for the activity (for more details check this ). 您必须使用不受限制的服务,该服务对于活动是完全独立的(有关更多详细信息,请检查 )。 After starting service monitor your internet connection using ConnectivityManager. 启动服务后,使用ConnectivityManager监视Internet连接。 Use this like example. 使用这种类似的例子。 Have Fun. 玩得开心。

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

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