2020年6月29日
? 項(xiàng)目需求:需要監(jiān)聽(tīng)文件發(fā)生的改動(dòng)(.txt)文件,當(dāng)文件發(fā)生變化時(shí)讀取并進(jìn)行相應(yīng)的處理
? 方案設(shè)計(jì):
? ? (1)開(kāi)啟線程,定時(shí)讀取該文件,檢測(cè)是否該文件發(fā)生變化。
? ? (2)尋找可以監(jiān)聽(tīng)文件變化的系統(tǒng)API,找到FileObserver這個(gè)系統(tǒng)API
使用方式
? ```js
package com.dudu.mylibrary;
import android.content.Context;
import android.os.FileObserver;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* <pre>
*? ? @author : hanshizhe
*? ? e-mail? : hanshizhe@foxmail.com
*? ? time? ? : 2020/6/28 11:54
*? ? desc? ? : 文件監(jiān)聽(tīng)修改器
* </pre>
*/
public class FileModifyObserver extends FileObserver {
? ? private Context mContext;
? ? private OnLookListener mListener;
? ? public FileModifyObserver(Context context,String path,OnLookListener listener) {
? ? ? ? super(path,FileObserver.ALL_EVENTS);
? ? ? ? this.mContext = context;
? ? ? ? this.mListener = listener;
? ? }
? ? @Override
? ? public void onEvent(int event, @Nullable String path) {
? ? ? ? Log.d("MakeMyJar_APP",event+"監(jiān)控文件");
? ? ? ? if(event == FileObserver.MODIFY){
? ? ? ? ? ? mListener.onSuccess(9999);
? ? ? ? }
? ? }
}
```?
? 調(diào)用方式:
```js
package com.dudu.mylibrary;
import android.content.Context;
/**
* <pre>
*? ? @author : hanshizhe
*? ? e-mail? : hanshizhe@foxmail.com
*? ? time? ? : 2020/6/28 11:25
*? ? desc? ? :
* </pre>
*/
public class LookHelper {
? ? //重點(diǎn)--生成全局變量,防止系統(tǒng)回收
? ? public static FileModifyObserver fileModifyObserver;
? ? public static void doLook(LookConfig config,OnLookListener listener){
? ? ? ? //獲取相應(yīng)的參數(shù)
? ? ? ? Context context? = config.getContext();
? ? ? ? String? filePath = config.getFilePath();
? ? ? ? //開(kāi)始文件監(jiān)聽(tīng)工作
? ? ? ? fileModifyObserver = new FileModifyObserver(context,filePath,listener);
? ? ? ? fileModifyObserver.startWatching();
? ? }
}
```?
? 問(wèn)題:1. 多次測(cè)驗(yàn)過(guò)程中,出現(xiàn)文件變化監(jiān)控不到的情況,生成全局變量即可
? 參考:
[Android FileObserver 監(jiān)聽(tīng)文件變化](http://www.itdecent.cn/p/a509ad4311c0)
[Android中的FileObserver監(jiān)聽(tīng)無(wú)效](https://www.cnblogs.com/chorm590/p/12370952.html)