Есть ли способ получить URI изображения сразу после его удаления из внешнего хранилища?

1

Я кодирую приложение галереи и впервые, когда приложение запускается, оно сканирует все внешнее хранилище, чтобы извлечь все изображения Uris и сохранить их в базе данных, чтобы при последующих запусках оно могло загружать их из своей собственной базы данных. Теперь мой вопрос, когда изображение удаляется, как я могу получить удаленное изображение Uri, чтобы уведомить галерею и обновить базу данных.

Я попробовал JobSchecular для случая, когда новое изображение добавляется через камеру, и оно отлично работает.

вот код

public class MediaJobSchedulerService extends JobService {

    private static final int ASJOBSERVICE_JOB_ID = 999;

    // A pre-built JobInfo we use for scheduling our job.
    private static JobInfo JOB_INFO = null;

    public static int a(Context context) {
        int schedule = (context.getSystemService(JobScheduler.class)).schedule(JOB_INFO);
        Log.i("PhotosContentJob", "JOB SCHEDULED!");
        return schedule;
    }

    // Schedule this job, replace any existing one.
    public static void scheduleJob(Context context) {
        if (JOB_INFO != null) {
            a(context);
        } else {
            JobScheduler js = context.getSystemService(JobScheduler.class);
            JobInfo.Builder builder = new JobInfo.Builder(ASJOBSERVICE_JOB_ID,
                new ComponentName(context, MediaJobSchedulerService.class));
            builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1));
            builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1));
            builder.setTriggerContentMaxDelay(500);
            JOB_INFO = builder.build();
            js.schedule(JOB_INFO);
        }
    }


    @Override
    public boolean onStartJob(final JobParameters params) {
        // Did we trigger due to a content change?
        final Context context = this;
        if (params.getTriggeredContentAuthorities() != null) {
            if (params.getTriggeredContentUris() != null) {
                // If we have details about which URIs changed, then iterate through them
                // and collect either the ids that were impacted or note that a generic
                // change has happened.
                final Repository repo = Repository.getInstance(this);
                ArrayList<String> ids = new ArrayList<>();
                for (final Uri uri : params.getTriggeredContentUris()) {
                    if (uri != null) {

                        Handler handler = new Handler();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {

                                if (!uri.toString().equals("content://media/external")) {
                                    Log.i("NEW_MEDIA", getRealPathFromUri(context, uri));
                                    repo.addImage(getRealPathFromUri(context, uri));
                                }
                            }
                        });
                    }
                }
                jobFinished(params, true); // see this, we are saying we just finished the job
                // We will emulate taking some time to do this work, so we can see batching happen.
                scheduleJob(this);
            }
        }
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

}

но в случае, когда изображение удалено, Uri отсутствует.

Моя огромная благодарность за вашу помощь.

Теги:

1 ответ

0

У Android нет и события для этого, но вы можете использовать и FileObserver. Это поймает удаление файла. Пример:

import android.os.FileObserver;
public class FileDeletedObserver extends FileObserver {
    public String absolutePath;
    public FileDeletedObserver(String path) {
        super(path, FileObserver.DELETE);
        absolutePath = path;
    }
    @Override
    public void onEvent(int event, String path) {
        if (path == null) {
            return;
        }

        if ((FileObserver.DELETE & event)!=0) {
            //handle deleted file
        }
    }
}
  • 0
    К сожалению, это не работает для меня, я пытался установить наблюдателя, в то время как Uris извлекается из хранилища форм следующим образом: FileDeletedObserver наблюдатель = новый FileDeletedObserver (imageAbsolutePath); observer.startWatching (); но до сих пор нет результатов

Ещё вопросы

Сообщество Overcoder
Наверх
Меню