Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I lock files in android using java code?

I want to lock files that is on the sdcard of android. I need to lock them so no one except my software can delete copy move or send them over bluetooth or any other way. How can I do it?

like image 323
Alex Kapustian Avatar asked Apr 30 '10 10:04

Alex Kapustian


People also ask

How do you lock a file in Java?

In Java, a file lock can be obtained using FileChannel , which provides two methods — lock() and tryLock() — for this purpose. The lock() method acquires an exclusive lock on entire file, whereas the lock(long position, long size, boolean shared) method can be used to acquire a lock on the given region of a ile.

How do you lock a file when writing?

As we've already learned, while writing to a file, we can prevent other processes from reading or writing to it by using an exclusive lock. We get exclusive locks by calling lock() or tryLock() on the FileChannel class.

What is Android file lock?

A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid.


1 Answers

There is no way to lock a file in Android; even if there was, the files would only be locked when your application was running which wouldn't stop other apps accessing the file when the user hadn't started your app.

SD Cards are usually formatted with FAT (or FAT32) and this is the case with Android. FAT offers very limited file permissions so you can't restrict access to the files this way. Again, even if you could do something like this, this wouldn't offer any protection if the user took the SD Card out of their phone and put it their PC.

If you want to keep your application's files private you need to put them in the phone's internal storage in the area reserved for you application. Each application runs with a different User ID and each application's data directory is protected using UNIX-style file permissions which prevents other applications from reading them. So while this will stop other applications having access to your files it wouldn't stop a reasonably determined user with root access to their phone copying them off.

Have a look at the Context.openFileInput(), Content.openFileOutput() and Context.getFilesDir() methods for details on how to store files in the phone's internal storage.

like image 129
Dave Webb Avatar answered Oct 30 '22 17:10

Dave Webb