Implementation code of Android monitoring SD card file changes

Android system API provides fileobserver abstract class (inotify mechanism of Linux) to monitor files or folders in the system / sdcard. Fileobserver class can monitor the opening, creation, movement and deletion of files and folders in sdcard. Let's look at the code implementation:

(1) To create a directory listener:

(2) Set listener for directory:

matters needing attention:

The fileobserver object must maintain a reference to ensure that it is not recycled by the garbage collector, otherwise the event will not be triggered. Here, you can consider using the service service.

2 if you want to do more operations in onevent, you'd better use threads to do so, so as not to receive subsequent events due to blocking.

3. Hyacinth has been tested. When the file information in the subfolder under a folder monitored by fileobserver is changed, the path provided is only the path of the subfolder, not the path of the specific file. Therefore, when you want to monitor the operation of all files, it is best to set fileobserver monitoring for each folder, which can be specific to the modification of each file, Otherwise, some applications will not be able to listen after modifying files. For example, the sdcard file directory has been monitored. When the gallery modifies / sdcard / xxx, it will be monitored. When the gallery operates on / sdcard / demo / XXXX, it will not be monitored. It is best to set fileobserver monitoring for / sdcard and / sdcard / demo to solve this problem.

Note: this method is only tested when the sdcard has about 20 folders. It is unclear whether too many folders will affect too many efficiency. I found that dbank also monitored several fixed folders containing pictures

PS: the following is a trilogy of monitoring SD card status

The first step is to create a broadcast receiver,

Step 2: register the corresponding action when the broadcast receiver and the SD card status change in the androidmanifest.xml configuration file:

Step 3: rewrite the onreceiver method in the broadcast receiver:

summary

The above is the implementation code of Android monitoring SD card file changes introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>