gpt4 book ai didi

安卓后台线程

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:16 25 4
gpt4 key购买 nike

我正在制作图像处理器应用。我需要扫描手机中的图片并列出它们的像素数。所以这会对性能产生很大影响,据我所知,我需要让它在后台线程上运行。

所以我的问题是,最好的方法是什么?我知道 IntentService 可能是最好的解决方案,但我不确定我将如何用它来实现进度条,我需要返回 Picture 对象,然后在随机播放按钮上更新 UI。我正在使用 Glide 库进行更新,这样会很顺利。

阅读有关 Asynctasks 的文章时,我无意中发现它的坏处和导致内存泄漏的评论,应该避免使用它。 rXJava 目前太复杂了。 这是我的代码:

主要 Activity :

@OnClick(R.id.shuffle)
public void shuffleList() {
Collections.shuffle(listOfImageFiles);
recyclerViewAdapter = new PictureRecycleViewAdapter(listOfImageFiles, this);
recyclerView.swapAdapter(recyclerViewAdapter, false);
recyclerViewAdapter.notifyDataSetChanged();
}

@OnClick(R.id.scan)
public void processImages() {

//progress bar

listOfPictures = new ArrayList<>();

//Gets data from default camera roll directory. Note that some of the phone companies have different file paths. So instead of hardcoding string paths, I used this instead.
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
File filePath = new File(path);
listOfImageFiles = scanPhotos(filePath);

// async?
for (File file : listOfImageFiles
) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());

//int is sufficient for most today's pixels. long would be overkill - 4 vs 8 bytes
int pixels = bitmap.getHeight() * bitmap.getWidth();

listOfPictures.add(new Picture(file.getPath(), pixels));
}
}

public List<File> scanPhotos(File directory) {
List<File> listOfPictures = new ArrayList<>();
try {
File[] files = directory.listFiles();
for (File file : files
) {
if (file.isDirectory() && !file.isHidden()) {
listOfPictures.addAll(scanPhotos(file));
} else {
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg") || file.getName().endsWith(".png")) {
listOfPictures.add(file);
}
}
}
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}

return listOfPictures;
}

最佳答案

Intent 服务

IntentService绝对是一种有效的方法。您可以使用Broadcasts 将您的结果返回到应用程序的另一个组件,无论是 Activity 还是其他服务,例如:

  1. 启动 IntentService - 如果您需要一些参数,请将它们放在服务 Intent 的 Extras 中。
  2. 你的 IntentService在后台线程上运行,直到计算完成。
  3. 完成后,发送一个广播,计算结果放在 intent extras 中。
  4. 在您的 Activity 中,注册 BroadcastReceiver它将监听您的计算结果广播。
  5. 在您的 Activity 收到广播后, 从 intent extras 中获取计算结果。

您还可以实现您的服务接收的广播,用于取消计算或更新参数等。

IntentService的优势之一是您可以轻松地将它与 JobScheduler 集成延迟执行直到满足特定系统条件的 API。

备选方案

  • 您可以使用总线库,例如 https://github.com/greenrobot/EventBus Activity之间进行沟通和 Service - 唯一的问题是,EventBus 不能与远程服务一起工作(在单独的进程中运行)。

  • 正如您提到的,将 RxJava 与IO计算 调度程序一起使用也是一个好主意。

  • AsyncTask只要您不将它与对 Activity 的硬引用联系起来就可以了——不要将其实现为 Activity 的内部类,如果您想返回结果,请通过 WeakReference<T> 进行。

关于安卓后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com