MediaScannerConnection导致android.app.ServiceConnectionLeaked错误。

29

我正在使用来自API Demos的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);
        }
});
当我运行这段代码时,我从LogCat中得到一个FC对话框,其内容如下:LogCat
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

我哪里做错了?

顺便提一下,我是在使用AsyncTask的后台线程上运行这个程序的。


1
我有一种感觉,MediaScannerConnection泄漏了监听器。不知何故,它没有被清理,并且没有重置监听器的方法。我目前也面临着同样的问题。你在这段时间里解决了吗? - eMich
我不记得了。我是一年前发布的。我得回去检查一下。 - David Shellabarger
我仍然在KitKat上看到这个问题。相信这是一个Android问题,而不是使用问题。 - Justin
3个回答

29

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

代码按预期正常工作,使设备图库中的新文件可见,但同时打印有关leaked ServiceConnection的错误信息。

查看MediaScannerConnection的内部Android代码,似乎存在某种机制来在最后一个文件之后停止服务。也许仅给定一个文件时它不起作用?

最终,我通过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

看起来这是首选方式,并且在Android关于拍照的培训中也提到了。


12
请使用getApplicationContext()代替。

1
很好的答案。使用IntentService可以消除泄漏问题。 - Medo
在非意图服务中也能很好地工作! - ohaleck

0

我在更改布局时,语音识别器出现了问题。

我所要做的就是添加一个unregisterReceiver,就像在onActivityResult中这样:

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    unregisterReceiver(mReceiver);
    super.onDestroy();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接