Android 通知权限

>> 在 AndroID 13 中引入了通知权限: android.permission.POST_NOTIFICATIONS

     在 AndroID 13 之前,可以直接通过 NotificationCenter 控件来发送消息; 

     在 AndroID 13 之后,需要动态申请此权限,才可以发送通知;

>> 动态权限申请 

procedure TForm1.Button1Click(Sender: TObject);
var
  tmpPermissions: TArray<string>;
begin
  // 从AndroID 13 开始,通知权限需要申请
  if TJBuild_Version.JavaClass.SDK_INT > 32 then
  begin
    tmpPermissions :=
      [JStringToString(TJManifest_permission.JavaClass.POST_NOTIFICATIONS)];
    // 申请权限
    Permissionsservice.RequestPermissions(tmpPermissions,
      RequestPermissionsResult, DisplayRationale);
  end
  else  //低于此版本的,直接发送通知
    SendNotification;
end;

  ***  若只是动态 申请,经测试,在AndroID14手机上,还是无法弹出授权弹窗;

  ***  经查,需要在 AndroidManifest.xml 文档中,要申请通知权限,之后在代码中动态申请权限,才会弹窗;

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

 

>> 通知发送

procedure TForm1.SendNotification;
var
  tmpNotification: TNotification;
  tmpDelay: Integer;
begin
  // tmpNotification := TNotification.Create;
  tmpNotification := NotificationCenter1.CreateNotification;
  try
    tmpNotification.Name := edt_Name.Text; // 唯一
    tmpNotification.Title := edt_Title.Text; // 标题
    tmpNotification.AlertBody := edt_Body.Text; // 名称

    tmpNotification.Number := 66; //数量

    tmpNotification.AlertAction := '查看来源';
    tmpNotification.HasAction := True;

    tmpDelay := StrToIntDef(edt_Delay.Text, 0);
    if tmpDelay > 0 then
    begin
      tmpNotification.FireDate := IncSecond(Now, tmpDelay);
      NotificationCenter1.ScheduleNotification(tmpNotification)
    end
    else
      NotificationCenter1.PresentNotification(tmpNotification);
  finally
    tmpNotification.Free;
  end;
end;

 

posted @ 2024-12-08 15:41  耗喜天涯  阅读(925)  评论(0)    收藏  举报