【问题标题】:How to call a method in full life time of the application如何在应用程序的整个生命周期中调用方法
【发布时间】:2013-09-10 01:32:25
【问题描述】:
我正在开发示例应用程序,它有一个 sqlite 和 mysql 数据库。如果 Internet 连接有数据进入 Web 服务器数据库(mysql 数据库),如果没有 Internet 连接数据保存 sqlite 数据库,在重新打开与 Web 服务器数据库(mysql 数据库)同步的应用程序后,现在我想同步 Web 服务器数据库( mysql 数据库)在不重新打开应用程序的情况下,应用程序的运行时间应该是同步的。帮帮我
【问题讨论】:
标签:
android
android-sqlite
android-syncadapter
android-backup-service
【解决方案1】:
使用BroadcastReceiver 并在AndroidManifest 中声明它...
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
你还需要...
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
...在清单中。
在BroadcastReceiver 的onReceive(...) 方法中检查Intent 以查看发生了什么变化 - 如果它已更改为已连接,则可以开始同步操作。
要执行同步,请使用IntentService,它将在工作线程上执行工作,然后在工作完成后自行终止。
如果您想要定期备份,您还应该考虑使用AlarmManager 创建一个可用于定期触发IntentService 的重复警报。在这种情况下,IntentService 显然必须执行显式检查以查看是否有可用的 Internet 连接。