FileObsever实现文件监听

有时候有需求需要监听文件是否被修改,可以使用android提供的FileObsever API进行监控,具体使用方法如下:

创建文件监听类:

package com.example.androidinterviewjxd.io;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.FileObserver;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.io.File;
import java.util.List;

public class MyFileObsever extends FileObserver {
    private Context context;
    /**
     * Equivalent to FileObserver(file, FileObserver.ALL_EVENTS).
     *
     * @param file
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public MyFileObsever(@NonNull File file, Context context) {
        super(file,FileObserver.ALL_EVENTS);
        this.context = context;
    }

    /**
     * The event handler, which must be implemented by subclasses.
     *
     * <p class="note">This method is invoked on a special FileObserver thread.
     * It runs independently of any threads, so take care to use appropriate
     * synchronization!  Consider using {@link Handler#post(Runnable)} to shift
     * event handling work to the main thread to avoid concurrency problems.</p>
     *
     * <p>Event handlers must not throw exceptions.</p>
     *
     * @param event The type of event which happened
     * @param path  The path, relative to the main monitored file or directory,
     *              of the file or directory which triggered the event.  This value can
     *              be {@code null} for certain events, such as {@link #MOVE_SELF}.
     */
    @Override
    public void onEvent(final int event, @Nullable String path) {
        Log.d("FileObseverTest","event "+event);
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context,"event "+event,Toast.LENGTH_SHORT).show();
            }
        });
    }
}

在activity中进行调用:

package com.example.androidinterviewjxd.io;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.androidinterviewjxd.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileObseverActivity extends AppCompatActivity {
    private File file = null;
    private MyFileObsever myFileObsever = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_obsever);
        file = new File(getExternalCacheDir().getAbsolutePath()+File.separator+"test.txt");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            myFileObsever = new MyFileObsever(file,FileObseverActivity.this);
            myFileObsever.startWatching();
        }
    }

    public void createFile(View v){
        try {
            if(!file.exists())
                file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteFile(View v){
        try {
            if(file.exists())
                file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void modifyFile(View v){
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath(),true);
            fileOutputStream.write("dddd".getBytes());
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".io.FileObseverActivity">

    <Button
        android:id="@+id/create_file_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:text="创建文件"
        android:onClick="createFile"
        />
    <Button
        android:id="@+id/delete_file_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除文件"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/create_file_btn"
        android:onClick="deleteFile"
        />
    <Button
        android:id="@+id/modify_file_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改文件"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/delete_file_btn"
        android:onClick="modifyFile"
        />



</androidx.constraintlayout.widget.ConstraintLayout>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

景兄弟1366

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值