【问题标题】:Should I close the cursor when exiting IntentService?退出 IntentService 时是否应该关闭光标?
【发布时间】:2015-04-13 21:08:08
【问题描述】:

我很确定 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...
    }
}

【问题讨论】:

  • 当然可以。每当 Cursor 不再使用时,应立即将其关闭。
  • 感谢您的回答。

标签: android android-contentprovider android-cursor android-intentservice


【解决方案1】:

每次使用游标时,都应将其包裹在 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

【讨论】:

  • 对,我忘了例外。 try 块将完成这项工作。谢谢你。希望我能支持你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2015-08-08
相关资源
最近更新 更多