在MainActivity.class
内,我在手机上引用了.docx文件
//Reference to the file
File targetFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/storage/sdcard0/My Folder/Android-tutorial.docx");
//I start the background service here.
startService(new Intent(getApplicationContext(), FileObserverService.class).putExtra("INTENT_EXTRA_FILEPATH", targetFile.getAbsolutePath()));
//To open file in external app
Uri targetUri = Uri.fromFile(targetFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/*");
startActivityForResult(intent, 100);
“我的服务”类用于监视文件更改。在外部应用程序中打开.docx文件时,仅会触发OPEN事件。即使更改文件内容并将其从外部应用程序保存,也不会触发MODIFY事件。
public class FileObserverService extends Service {
private FileObserver mFileObserver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
final String pathToFile = intent.getStringExtra("INTENT_EXTRA_FILEPATH");
new FileObserver(pathToFile) {
@Override
public void onEvent(int event, String path) {
switch (event) {
case FileObserver.OPEN:
Log.d("FILEOBSERVER_OPEN", "Event with id " + Integer.toHexString(event) + " happened");
break;
case FileObserver.MODIFY:
Log.d("FILEOBSERVER_MODIFY", "Event with id " + Integer.toHexString(event) + " happened");
break;
case FileObserver.CLOSE_WRITE:
Log.d("FILEOBSERVER_CLOWRITE", "Event with id " + Integer.toHexString(event) + " happened");
break;
case FileObserver.DELETE:
Log.d("FILEOBSERVER_DELETE", "Event with id " + Integer.toHexString(event) + " happened");
break;
}
}
}.startWatching();
}catch (Exception e){
e.printStackTrace();
}
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
输出:
D/FILEOBSERVER_OPEN: Event with id 20 happened