我已在三部手机上试过了,但我的FileObserver只能在适用于Android 4.2.2的手机上运行,并且无法在其他版本上捕获任何事件。这是我的代码: 在AndroidMenifest中我已经添加了使用权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在活动中,像这样:
static class DownloadObserver extends FileObserver {
public DownloadObserver(String path) {
super(path);
}
@Override
public void onEvent(int event, String path) {
switch (event) {
case FileObserver.MODIFY:
Log.e(TAG, ":MODIFY");
break;
case FileObserver.ACCESS:
Log.e(TAG, ":ACCESS");
break;
case FileObserver.CREATE:
Log.e(TAG, ":CREATE");
break;
default:
Log.e(TAG, ":default");
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
request = new DownloadManager.Request(Uri.parse(PACKAGE_URL))
.setAllowedOverRoaming(false)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setVisibleInDownloadsUi(true)
.setDestinationInExternalPublicDir("/download/", getVersionName() + ".apk");
manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getVersionName() + ".apk");
Log.e(TAG, "file.getParent() = " + file.getParent());
observer = new DownloadObserver(file.getParent());
observer.startWatching();
mTaskId = manager.enqueue(request);
}
@Override
protected void onDestroy() {
super.onDestroy();
observer2.stopWatching();
}