【发布时间】:2018-11-19 11:51:31
【问题描述】:
我有一个获取 FCM 数据消息(包含图像 URL)的 android 应用程序。
当onMessageReceived() 接收到数据消息时,我创建了一个FirebaseJobDispatcher 和一个作业,然后安排作业以将图像下载并保存到本地存储dispatcher.mustSchedule(myJob)。
下载和保存图像作业扩展JobService。启动作业时,我创建一个线程,在其中下载并保存图像,然后向 Activity 发送BroadcastReceiver,以便它使用 Picasso 显示来自本地存储的新图像 ImageView(下面的代码):
private String imageName = "image.jpg";
@Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d(TAG, "Update local storage content with new Image!");
Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
// Delegating work to a new Thread since it can be long task (downloading Image and storing it to local file system)
Thread storeImageThread = new Thread(new Runnable() {
@Override
public void run() {
// File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageName);
File file = new File(getApplicationContext().getFilesDir(), imageName);
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.flush();
ostream.close();
} catch (IOException e) {
e.getLocalizedMessage();
}finally {
Intent intent = new Intent("com.example.SendBroadcast");
//intent.putExtra("imageURL", remoteMessage.getData().get("image"));
intent.setAction("com.example.SendBroadcast");
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// sendBroadcast(intent);
sendOrderedBroadcast(intent,null);
//Tell the framework that the job has completed and does not need to be reschedule
jobFinished(jobParameters, true);
}
}
});
storeImageThread.start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(getApplicationContext())
.load(jobParameters.getExtras().getString("image"))
.into(target);
return true;
}
我在这个架构上遇到了一些问题;
- 尽管我使用 setTrigger(Trigger.executionWindow(0, 0)),但 Job Service 多次启动很晚。那么我应该使用带有 Job Service 的 Firebase Job Dispatcher 来下载图像并将其保存在本地存储中吗?还有其他选择吗?
在完成下载和保存图像后,是否有更高效、更高效的方式来更新 Activity?
我认为 Picasso 使用单独的线程来下载图像,那么我这里使用的线程是否正确?
我多次收到 ARN 对话框和应用程序崩溃。那么有没有更适合我的性能架构建议?
提前感谢专家的帮助
【问题讨论】:
-
有专家支持吗?
标签: android firebase-cloud-messaging android-broadcastreceiver android-jobscheduler firebase-job-dispatcher