我有问题,FIleObserver和ContentObserver都无法在
Android Marshmallow中运行.我正在使用这个东西来检测文件夹内发生的变化.我为marshmallow设置了运行时权限.但在那之后它也没有显示任何事件.它在其他版本中完美运行.请帮我解决这个问题.
首先,我尝试在Service中使用Content Resolver来检测后台中的文件夹更改.
public class TestService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent,int flags,int startId) { initial(); return START_STICKY; } public void initial(){ getContentResolver().registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,true,new ContentObserver(new Handler()) { @Override public boolean deliverSelfNotifications() { Log.d("hai","deliverSelfNotifications"); return super.deliverSelfNotifications(); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); } @Override public void onChange(boolean selfChange,Uri uri) { if (uri.toString().matches(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString() + "/[0-9]+")) { Cursor cursor = null; try { cursor = getContentResolver().query(uri,new String[] { MediaStore.Images.Media.DISPLAY_NAME,MediaStore.Images.Media.DATA },null,null); if (cursor != null && cursor.moveToFirst()) { final String fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)); final String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); // TODO: apply filter on the file name to ensure it's screen shot event Log.d("file","FILE CHANGE OCCURED " + fileName + " " + path); } } finally { if (cursor != null) { cursor.close(); } } } super.onChange(selfChange,uri); } } ); } }
并运行时权限为:
private void getPermission(){ boolean hasPermission = (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermission) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_READ_STORAGE); } }
并获得了权限导致onRequestPermissionsResult.
这种方法对我不起作用.所以我在该服务中尝试使用FileObserver.那个时候它也适用于所有其他平台,但不适用于Marshmallow.