You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI Android端使用Preferences崩溃问题咨询

Android端访问Preferences的常规方式及问题排查

一、原生Android开发的常规实现

Android平台提供两种主流的偏好存储方案,无需额外权限即可使用:

1. SharedPreferences(传统兼容方案)

这是最常用的轻量级存储方式,步骤如下:

  • 获取实例:
    • 全局共享(全应用可访问):
      SharedPreferences prefs = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE);
      
    • Activity专属(仅当前Activity可用):
      SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
      
  • 写入数据:必须通过Editor对象操作,推荐用异步的apply()提交:
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("user_setting", "dark_mode");
    editor.putBoolean("auto_sync", true);
    editor.apply(); // 异步提交,不阻塞线程
    
  • 读取数据:直接调用对应类型的get方法,传入默认值避免空指针:
    String theme = prefs.getString("user_setting", "light_mode");
    boolean syncEnabled = prefs.getBoolean("auto_sync", false);
    

2. Jetpack DataStore(现代推荐方案)

替代SharedPreferences的官方新方案,基于Flow实现异步、线程安全的存储,适合复杂场景:

// 定义键
object PreferencesKeys {
    val USER_THEME = stringPreferencesKey("user_setting")
    val AUTO_SYNC = booleanPreferencesKey("auto_sync")
}

// 获取DataStore实例
val dataStore = context.createDataStore(name = "app_prefs")

// 写入数据
dataStore.edit { preferences ->
    preferences[PreferencesKeys.USER_THEME] = "dark_mode"
    preferences[PreferencesKeys.AUTO_SYNC] = true
}

// 读取数据(通过Flow监听变化)
val themeFlow = dataStore.data
    .map { preferences ->
        preferences[PreferencesKeys.USER_THEME] ?: "light_mode"
    }

二、跨平台开发场景(如.NET MAUI/Xamarin)的注意事项

你提到Windows端正常、Android端崩溃,大概率是使用了跨平台框架的通用Preferences抽象层,此时需注意:

  1. 优先使用框架提供的通用API:
    以.NET MAUI为例,通用用法如下:
    // 写入
    Preferences.Set("user_setting", "dark_mode");
    // 读取
    string theme = Preferences.Get("user_setting", "light_mode");
    
  2. 崩溃原因及解决:
    通用API在Android端崩溃,通常是框架兼容性问题,此时可以改用平台特定代码直接调用Android原生API:
    #if ANDROID
    using Android.Content;
    using Android.Preferences;
    
    // 获取当前Activity的Context
    var context = Platform.CurrentActivity;
    var prefs = PreferenceManager.GetDefaultSharedPreferences(context);
    
    // 写入
    var editor = prefs.Edit();
    editor.PutString("user_setting", "dark_mode");
    editor.Apply();
    
    // 读取
    string theme = prefs.GetString("user_setting", "light_mode");
    #endif
    

三、是否需要特定平台方法?

  • 原生Android开发:直接使用SharedPreferences或Jetpack DataStore即可,这就是Android平台的标准方式。
  • 跨平台开发:优先用框架通用API,遇到兼容性问题时,通过平台特定代码调用Android原生存储方案即可解决。

内容的提问来源于stack exchange,提问作者user3017691

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:24:50