简体   繁体   English

在片段中使用 MediaScannerConnection.scanFile()?

[英]Using MediaScannerConnection.scanFile() in a fragment?

I am downloading a file from within a Fragment asynchronously and would like to call MediaScannerConnection.scanFile() when the download completes.我正在从Fragment异步下载文件,并希望在下载完成时调用MediaScannerConnection.scanFile() I am able to get desired results if I sit and wait for the download to finish without navigating away from my Fragment (or its hosting activity).如果我坐下来等待下载完成而不离开我的 Fragment(或其托管活动),我就能获得想要的结果。 The problem I am facing is that MediaScannerConnection.scanFile() requires a context and I don't want to limit the user to staying within a Fragment / Activity just so that context is not null.我面临的问题是MediaScannerConnection.scanFile()需要一个上下文,我不想将用户限制在Fragment / Activity只是为了使上下文不为空。

How do I make use of MediaScannerConnection.scanFile() in the background so that I can scan the files and display a Toast when the scanning is complete while still navigating in other parts of my app (or even tabbing out of my app)?如何在后台使用MediaScannerConnection.scanFile()以便我可以扫描文件并在扫描完成时显示Toast ,同时仍在我的应用程序的其他部分导航(甚至跳出我的应用程序)?

This is how I am currently scanning (with a context):这就是我目前正在扫描的方式(带有上下文):

public static void mediaScanFile(Context context, String path) {
    MediaScannerConnection.scanFile(context,
            new String[]{path}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
                }
            });
}

First of all, downloading a file from a Fragment which may be destroyed soon is not a good idea.首先,从可能很快被破坏的Fragment下载文件不是一个好主意。 You should use foreground service instead.您应该改用前台服务


If you still want to stick with fragments, in your case, you can make use of the application context.如果您仍然想坚持使用片段,在您的情况下,您可以使用应用程序上下文。

Before starting the download, store a reference of the application context as a field in your fragment.在开始下载之前,将应用程序上下文的引用存储为片段中的字段。

Context appContext;

// Inside onCreateView
appContext = getContext().getApplicationContext();

Then you can use the application context for scanning media.然后您可以使用应用程序上下文来扫描媒体。

This won't cause memory leak because the application context is a single shared instance and won't be destroyed until the app is killed.这不会导致内存泄漏,因为应用程序上下文是单个共享实例,并且在应用程序被终止之前不会被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM