工具類 sendInformation 中調用 getContentResolver() 報錯:方法未定義。
getContentResolver() 是 Context 方法,普通 Java 類無此方法。
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();
context.getApplicationContext() 防止 Activity 洩漏,ContentResolver 不依賴 Activity 生命周期。static void test(Context context)。android:exported="true" 或簽名權限。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 內存洩漏。android:multiprocess 與權限保護級別。ContentProviderOperation + applyBatch() 事務性執行。非 Context 類訪問 ContentResolver 鐵律:構造函數注入 Context → 持有 ApplicationContext → 調用 context.getContentResolver(),與訪問 Resources 完全一致。