如何在Android中实现跨进程锁? [英] How to implement cross process lock in android?

查看:1467
本文介绍了如何在Android中实现跨进程锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个库项目的多个应用程序使用。出于某种原因,我必须做出一个功能互斥针对不同的应用程序,所以我需要一个跨进程锁。但据我所知,在Android应用程序只能写在内部存储它自己的文件所在的目录,和外部存储是不可靠的,因为有些设备不具备的。所以文件锁似乎并不适用于我,所以有没有实现跨进程锁定任何其他方式?

I'm writing a library project for multiple APPs to use. And for some reason, I must make a function mutual exclusion for different APPs, so I need a cross-process lock. But as far as I know, in android APPs can only write to it's own file's directory in internal storage, and external storage is unreliable because some device don't have one. So file lock seems not applicable for me, so is there any other way to implement cross-process lock?

谢谢〜

推荐答案

如果您不想(或不能)用羊群或的fcntl,也许你可以使用LocalServerSocket来实现自旋锁。 例如:

If you do not want to (or you can not) use flock or fcntl, maybe you can use LocalServerSocket to implement a spinlock. For example:

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;
}

这篇关于如何在Android中实现跨进程锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆