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

Delphi 10.4开发Sunmi L2s安卓App接收扫码广播报错求助

报错修复&扫码功能实现方案

错误原因说明

  1. 启动报External exception 0是因为空指针未处理、函数返回值未赋值,以及子线程直接操作UI导致的异常
  2. 收不到扫码广播是因为两个配置不匹配:
    • 注册的广播Action和判断用的Action不一致
    • 扫码结果的Extra字段名写错,安卓系统字段大小写敏感

修正后的完整代码

implementation

{$R *.fmx}

uses
  FMX.Platform.Android, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net,  
  Androidapi.JNI.Os, Androidapi.Helpers, System.Classes;

const
  // 统一商米扫码广播常量,避免拼写错误
  SCAN_ACTION = 'com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED';
  SCAN_EXTRA = 'data';

procedure TForm4.FormCreate(Sender: TObject);
var
  AppEventService: IFMXApplicationEventService;
begin
  if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, AppEventService) then
    AppEventService.SetApplicationEventHandler(HandleAppEvent);
      
  MainActivity.registerIntentAction(StringToJString(SCAN_ACTION));
  TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedNotification, HandleActivityMessage);
end;

procedure TForm4.HandleActivityMessage(const Sender: TObject; const M: TMessage);
begin
  if M is TMessageReceivedNotification then
    HandleIntentAction(TMessageReceivedNotification(M).Value);
end;

function TForm4.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
var
  StartupIntent: JIntent;
begin
  Result := False;
  if AAppEvent = TApplicationEvent.BecameActive then
  begin
    StartupIntent := MainActivity.getIntent;
    if StartupIntent <> nil then
      HandleIntentAction(StartupIntent);
    // 事件处理完成标记返回值
    Result := True;
  end;
end;

function TForm4.HandleIntentAction(const Data: JIntent): Boolean;
var
  JStr: JString;
  ScanResult: string;
begin
  Result := False;
  // 用统一常量判断Action,避免拼写错误
  if (Data <> nil) and Data.getAction.equals(StringToJString(SCAN_ACTION)) then
  begin
    JStr := Data.getStringExtra(StringToJString(SCAN_EXTRA));
    // 做空值判断避免空指针异常
    if JStr <> nil then
    begin
      ScanResult := JStringToString(JStr);
      // 强制在主线程更新UI,避免线程冲突报错
      TThread.Synchronize(nil,
        procedure
        begin
          Label1.Text := ScanResult;
        end
      );
      Result := True;
    end;
  end;
end;

end.

额外配置检查

  • 打开项目的安卓配置页面,在权限列表中添加com.sunmi.permission.SCANNER权限,避免部分商米系统版本拦截广播
  • 测试前先确认系统扫码功能正常:按下橙色扫码按钮能弹出扫码框,在系统记事本页面按下扫码按钮能正常输出条码内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:24:02