有时候有需求需要监听文件是否被修改,可以使用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>