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

SpellCheckerSession.isSessionDisconnected()总是返回true 拼写建议方法失效

问题根源

SpellCheckerSession的初始化是异步绑定系统服务的过程,你在调用newSpellCheckerSession后立刻检查会话状态、发起查询请求,此时服务还未完成绑定,isSessionDisconnected自然返回true,所有查询方法都无法生效。

修复方案

1. 先确认基础配置正常

  • 设备系统设置中已开启拼写检查服务:路径为「系统设置→语言和输入法→拼写检查」
  • 你使用的Locale.ENGLISH在当前设备有对应的拼写检查规则支持
  • 当前类已正确实现SpellCheckerSession.SpellCheckerSessionListener接口

2. 调整代码逻辑,避免同步调用查询

不要在创建会话的同一代码块中立刻发起查询,等待会话绑定完成后再执行操作,参考修正代码:

final TextServicesManager tsm = (TextServicesManager) getSystemService(
        Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, Locale.ENGLISH, this, false);

// 延迟执行查询,等待服务绑定完成
new Handler(Looper.getMainLooper()).postDelayed(() -> {
    if (mScs == null || mScs.isSessionDisconnected()) {
        Log.e(TAG, "拼写检查会话不可用");
        return;
    }
    // 为每个查询实例化TextInfo
    // 可向TextInfo传递序列号和Cookie标识号以识别返回结果
    if (isSentenceSpellCheckSupported()) {
        // 注意getSentenceSuggestions仅支持JB及以上版本
        Log.d(TAG, "Sentence spellchecking supported.");
        mScs.getSentenceSuggestions(new TextInfo[]{new TextInfo("ber")}, 3);
        mScs.getSentenceSuggestions(new TextInfo[]{new TextInfo("casade")}, 3);
        mScs.getSentenceSuggestions(new TextInfo[]{new TextInfo("hell othere")}, 3);
    } else {
        // 注意getSuggestions()是已废弃的API
        // 建议运行在Jelly Bean及以上版本的应用仅调用getSentenceSuggestions()
        mScs.getSuggestions(new TextInfo("ber"), 3);
        mScs.getSuggestions(new TextInfo("hllo"), 3);
        mScs.getSuggestions(new TextInfo("helloworld"), 3);
    }
}, 200); // 延迟200ms,可根据设备性能调整

3. 额外注意事项

  • 页面销毁时要主动调用mScs.close()释放会话资源,避免内存泄漏
  • 拼写检查的结果会通过你实现的SpellCheckerSessionListener的对应回调方法返回,不要在发起查询的位置同步等待结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:24:04