MediaScannerConnection生成android.app.ServiceConnectionLeaked

Dav*_*ger 29 android sample

我正在使用API演示中的MediaScannerConnection示例代码

我正在使用的片段是:

MediaScannerConnection.scanFile(
    context,
    new String[] { permFile.getAbsolutePath() }, 
    null,
    new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {

            android.util.Log.i("ExternalStorage", "Scanned " + path + ":");
            android.util.Log.i("ExternalStorage", "-> uri=" + uri);
        }
});
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我从LogCat获得一个带有以下内容的FC对话框:

4-20 23:17:45.988: ERROR/ActivityThread(3015): Activity com.my.package.name has leaked ServiceConnection android.media.MediaScannerConnection@40715c70 that was originally bound here
04-20 23:17:45.988: ERROR/ActivityThread(3015): android.app.ServiceConnectionLeaked: Activity com.my.package.name has leaked ServiceConnection android.media.MediaScannerConnection@40715c70 that was originally bound here
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?仅供我使用AsyncTask从后台线程运行此功能.

sun*_*rer 29

我注意到使用Environment.getExternalStoragePublicDirectory文档提供的代码片段时出现了同样的错误消息.

代码正常工作,并在设备库中显示一个新文件,但同时打印有关的错误leaked ServiceConnection.

看看它的内部android代码MediaScannerConnection似乎存在某种机制来在最后一个文件之后停止服务.也许只给一个​​文件它不起作用?

我最终通过Intent通知MediaScanner使用了一个完全不同的解决方案.这也很好,并没有产生任何警告:

Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri fileContentUri = Uri.fromFile(permFile); // With 'permFile' being the File object
mediaScannerIntent.setData(fileContentUri);
this.sendBroadcast(mediaScannerIntent); // With 'this' being the context, e.g. the activity
Run Code Online (Sandbox Code Playgroud)

这似乎是首选方式,因为它在Android培训中也提到过拍摄照片.


Pep*_*ijn 11

getApplicationContext()改用.