首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 非 Activity 類使用 getContentResolver:構造函數傳遞 Context 獲取 ContentResolver

     編輯:程式設計綜合問答

問題現象

工具類 sendInformation 中調用 getContentResolver() 報錯:方法未定義。

根本原因

getContentResolver() 是 Context 方法,普通 Java 類無此方法。

解決方案:構造函數注入 Context

public class SendInformation {
    private Context context;
    
    public SendInformation(Context context) {
        this.context = context.getApplicationContext(); // 持有 ApplicationContext
    }
    
    public void test() {
        Uri uri = SuspiciousActivityTable.CONTENT_URI;
        // 正確:context.getContentResolver()
        context.getContentResolver().update(uri, values2, where, new String[]{"Null"});
    }
}

// Activity/Service 中使用
SendInformation sender = new SendInformation(this);
sender.test();

關鍵點

  • 持有 ApplicationContext:context.getApplicationContext() 防止 Activity 洩漏,ContentResolver 不依賴 Activity 生命周期。
  • 非靜態工具類:若為靜態方法,簽名改為 static void test(Context context)。
  • 權限:操作 ContentProvider 需在 Manifest 聲明 android:exported="true" 或簽名權限。

進階:單例封裝 ContentResolver 操作

public class ContentResolverHelper {
    private static ContentResolverHelper instance;
    private ContentResolver resolver;
    
    private ContentResolverHelper(Context context) {
        this.resolver = context.getApplicationContext().getContentResolver();
    }
    
    public static synchronized ContentResolverHelper getInstance(Context context) {
        if (instance == null) instance = new ContentResolverHelper(context);
        return instance;
    }
    
    public int update(Uri uri, ContentValues values, String where, String[] args) {
        return resolver.update(uri, values, where, args);
    }
    // query, insert, delete, openFileDescriptor 等封裝...
}

// 使用
ContentResolverHelper.getInstance(this).update(uri, values, where, args);

避坑指南

  • 不要在工具類靜態字段持有 Context context = this,導致 Activity 內存洩漏。
  • ContentResolver 跨進程訪問 ContentProvider 時,需關注 android:multiprocess 與權限保護級別。
  • 批量操作用 ContentProviderOperation + applyBatch() 事務性執行。

非 Context 類訪問 ContentResolver 鐵律:構造函數注入 Context → 持有 ApplicationContext → 調用 context.getContentResolver(),與訪問 Resources 完全一致。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved