如何在安卓系统中实现跨进程锁?

3

我正在为多个应用程序编写一个库项目。由于某些原因,我必须为不同的应用程序实现互斥功能,因此我需要一个跨进程锁。但据我所知,在Android应用程序中,只能写入其自己文件目录的内部存储器中,而外部存储器不可靠,因为某些设备没有外部存储器。因此,文件锁似乎对我不适用,那么有没有其他方法来实现跨进程锁呢?

谢谢~

1个回答

6
如果您不想或无法使用flock或fcntl,您可以尝试使用LocalServerSocket实现自旋锁。例如:
public class SocketLock {
    public SocketLock(String name) {
        mName = name;
    }

    public final synchronized void tryLock() throws IOException {
        if (mServer == null) {
            mServer = new LocalServerSocket(mName);
        } else {
            throw new IllegalStateException("tryLock but has locked");
        }
    }

    public final synchronized boolean timedLock(int ms) {
        long expiredTime = System.currentTimeMillis() + ms;

        while (true) {
            if (System.currentTimeMillis() > expiredTime) {
                return false;
            }
            try {
                try {
                    tryLock();
                    return true;
                } catch (IOException e) {
                    // ignore the exception
                }
                Thread.sleep(10, 0);
            } catch (InterruptedException e) {
                continue;
            }
        }
    }

    public final synchronized void lock() {
        while (true) {
            try {
                try {
                    tryLock();
                    return;
                } catch (IOException e) {
                    // ignore the exception
                }
                Thread.sleep(10, 0);
            } catch (InterruptedException e) {
                continue;
            }
        }
    }

    public final synchronized void release() {
        if (mServer != null) {
            try {
                mServer.close();
            } catch (IOException e) {
                // ignore the exception
            }
        }
    }

    private final String mName;

    private LocalServerSocket mServer;
}

谢谢!我简单测试了一下,似乎在我的手机上运行得相当不错:Sony Xperia M(Cyanogenmod 12.1) - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接