#java #android
#java #Android
Вопрос:
Я создаю приложение для галереи, и при первом запуске приложения оно сканирует все внешнее хранилище, чтобы получить все URI изображений, и сохраняет их в базе данных, чтобы при последующих запусках оно могло загружать их из своей собственной базы данных. Теперь мой вопрос: когда изображение удаляется, как я могу получить 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. Откуда вы будете удалять (удалять) изображение? В том же приложении?
2. @pavanShetty Нет из других источников устройства, таких как галерея по умолчанию или непосредственно из хранилища через файловый менеджер.
Ответ №1:
В Android для этого нет события and , но вы можете использовать and 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 amp; event)!=0) {
//handle deleted file
}
}
}
Комментарии:
1. К сожалению, у меня это не работает, я попытался установить observer, в то время как Uri извлекаются из хранилища следующим образом: FileDeletedObserver observer = new FileDeletedObserver (imageAbsolutePath); observer.startWatching(); но по-прежнему никаких результатов