2020-06-29

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)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容