运行 Android 中的背景循环

Run a loop on background in Android

我有一个功能,可以每两秒读取一次 Android 剪贴板的内容,并将所有更改与远程服务器进行通信。

这在应用程序打开时工作正常。但我需要能够在应用程序关闭后继续记录剪贴板更改。

所以我尝试了 IntentService 但它不喜欢长循环。

我怎样才能 运行 我在后台无限循环?

实施 Service 并通过在 onStartCommand 中返回 START_STICKY 使其具有粘性(参见 Documentation):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

I have a function that reads the content of the Android clipboard every two seconds and communicates all changes with a remote server.

轮询?你做的 非常 错了。您应该改用 OnPrimaryClipChangedListener

编辑

communicates all changes with a remote server.

我刚刚意识到你基本上在那里做了一些坏事,我有点怀疑你的用户是否知道你真的在监视他们?您的应用程序是否在 Google 中播放 如果是,您的应用程序包 ID 是多少?

IntentService 应该用于处理来自另一个应用程序组件的单个 "request"。

使用started service应该更适合你描述的问题。启动的服务会一直运行,直到您手动停止它或直到系统耗尽资源并终止整个进程。

使用START_STICKY as return from onStartCommand() 方法在系统终止时自动重新启动它。

如果您也在 BroadcastReceiver 中使用 ACTION_BOOT_COMPLETED 操作启动它,服务将在设备启动后启动。