Android StrictMode报告误报

Ste*_*anK 9 android android-strictmode

我一直在尝试在StrictMode中运行我的应用程序来检查可能已经潜入的任何隐藏问题.我遇到的一个问题是使用ContentResolver时泄漏的DatabaseConections似乎是误报.

经过一些实验后,问题简化为以下2行代码:

Cursor c = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cols, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);

c.close()
Run Code Online (Sandbox Code Playgroud)

上面的2行生成以下StrictMode违规:

ERROR/StrictMode(26219): Releasing cursor in a finalizer. Please ensure that you explicitly call close() on your cursor: 

ERROR/StrictMode(26219): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

ERROR/StrictMode(26219):
        at android.database.CursorWindow.<init>(CursorWindow.java:62)
        at android.content.ContentProviderProxy.query(ContentProviderNative.java:403)
        at android.content.ContentResolver.query(ContentResolver.java:302)
Run Code Online (Sandbox Code Playgroud)

我假设这是特定于Cursor由contentProvider返回的事实(因此它不是直接的SQLite游标).

有没有人有任何见解,如果这确实是一个误报或实际上是一个漏洞的光标.

Yur*_*ury 2

我想我可以解释一下问题出在哪里。当您查询数据库时,您可能会收到异常。因此,将创建一个 Cursor,c.close() 将不会被调用,因为存在异常。因此,您必须将 Cursor 的创建放在 try catch 块中,并在 finally 块中关闭 Curson。