2

我正在为 Android 开发无障碍服务。问题是,在模拟器(Android 4.0.5 API 15)上运行时,有时关闭服务时不会调用 onUnbind。发生这种情况时,无法停止服务,我需要重新安装 apk 或重新启动模拟器。

在实际设备(Galaxy Nexus)上运行此无障碍服务时,它工作正常。我无法重现此问题。

相关服务代码如下:

public class MyService extends AccessibilityService {
    boolean mRunning= false;

    private void init() {
        if (mRunning) {
            // if execution reaches this point means that onUnbind was
            // not called the last time the service has been switched off                    
            return;
        }

        /**
         * Unsubscribe all accessibility events. Cannot be removed directly from
         * @xml/accessibilityservice, otherwise onUnbind and onDestroy // never
         * get called
         */
        setServiceInfo(new AccessibilityServiceInfo());

        // Initialization stuff

        mRunning= true;
    }

    private void cleanup() {
        if (!mRunning) return;

        // cleanup stuff

        mRunning= false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onServiceConnected() {

        init();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        cleanup();

        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        cleanup();
    }
}

问题:

  • 我错过了什么吗?
  • 我能够检测到这种情况何时发生(请参阅有关 init() 的评论)。有没有办法强制服务停止?

额外细节:

  • 该服务包括一个本机部分并产生两个线程
  • 在模拟器上它消耗 100% 的 CPU,在 Galaxy Nexus 上大约 35%
  • 第一次失败后,无论服务打开和关闭多少次,onUnbind 都不会再次调用。
4

0 回答 0