让我们考虑一个Utility类,它的作用是预取Medias以供以后离线虚拟化。
现在我的班级是这样构建的:
public class MediaDownloadUtils {
public interface CallBack {
void callback(String fileFullPath);
}
public static void prefechMedia(final Context ctx, final Media media) {
Log.i("DWNDEBUG", "prefetching");
final String mediaId = media.getId();
downloadMedia(ctx, media, false, new CallBack() {
@Override
public void callback(final String fileName) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Media media2 = realm.where(CourseElement.class).equalTo("childType", CourseElementTypes.MEDIAS.name()).equalTo("id", mediaId).findFirst();
media2.setFilePath(fileName);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.i("renaud", "sucess !");
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.i("renaud", "error !");
}
});
} finally {
if (realm != null) {
realm.close();
}
realm = null;
}
}
});
}
public static void downloadMedia(final Context ctx, final Media media, boolean temp, CallBack cb) {...}
public static void dwnToFile(final Context ctx, final String link, final String fileName, final boolean temp, final CallBack cb) {...}
}
所以问题是:在哪里获得Realm?如果我把它作为一个参数传递,看起来我在回调中做我的事情会有问题,这将在不同的线程上。
如果我喜欢我的示例中显示的内容,我将不得不将回调线程变成一个更为松散的线程......我甚至不确定是否可行。
或者我应该将所有这些工作委托给原始启动器,并且每次都直接使用MediaDownloadUtils.downloadMedia()
来处理文件路径..
这些选项似乎都不是正确的,我应该如何组织这部分代码?
感谢您的帮助
编辑:解决方案
public class MediaDownloadUtils {
public interface CallBack {
void callback(String fileFullPath);
}
public static void prefechMedia(final Context ctx, final Media media, Realm realm) {
Handler handler = new Handler();
final String mediaId = media.getId();
downloadMedia(ctx, media, false, new CallBack() {
@Override
public void callback(final String fileName) {
handler.post(new Runnable() {
@Override
public void run() {
final Media media = realm.where(CourseElement.class).equalTo("childType", CourseElementTypes.MEDIAS.name()).equalTo("id", mediaId).findFirst();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Media media2 = realm.where(CourseElement.class).equalTo("childType", CourseElementTypes.MEDIAS.name()).equalTo("id", mediaId).findFirst();
media2.setFilePath(fileName);
}
});
}
});
}
public static void downloadMedia(final Context ctx, final Media media, boolean temp, CallBack cb) {...}
public static void dwnToFile(final Context ctx, final String link, final String fileName, final boolean temp, final CallBack cb) {...}
}