退出 IntentService 时应该关闭光标吗?

Should I close the cursor when exiting IntentService?

我很确定 cursor 已被 IntentService 实例销毁,但我只是想确保没有内存泄漏。如果这是一种正常的做法。我正在查询我的自定义 ContentProvider.

class MyService extends IntentService {
    protected void onHandleIntent(Intent intent) {
        Cursor cursor = getContentResolver().query(
                MyContentProvider.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() == 0) {
            return; // exit the method
        } else {
            cursor.close();
        }
        // some code...
    }
}

每次使用游标时,都应将其包裹在 try - finally 中并关闭它:

Cursor cursor = …;
if (cursor == null)
    return;
try {
    …
} finally {
    cursor.close();
}

这将确保即使抛出异常也不会发生内存泄漏。

Java 7 带来了 try-with-resources 但只有 Android API 19+ 支持它:

try (Cursor cursor = …)
{
    …
} // Cursor closed automatically