Перейти к содержанию
Fire Monkey от А до Я

Ingalime

Пользователи
  • Постов

    354
  • Зарегистрирован

  • Посещение

  • Победитель дней

    5

Сообщения, опубликованные Ingalime

  1. Цитата

    ищите устройство на котором падает

    Пока под рукой только андроид 8.1 Redmi 5A :(

    Цитата

    так же попробуйте вынести в кнопку код запуска сервиса.

    Теперь в кнопке Play в обновленном apk

    procedure TForm1.FormCreate(Sender: TObject);
    Begin
    
     if not BASS_Init(-1, 44100, 0, nil, nil) Then Begin
    	   ShowMessage('Failed to initialize audio!' + sLineBreak + 'Не удалось инициализировать audio!');
         Exit;
         end;
    End;
    
    procedure TForm1.Button1Click(Sender: TObject);
    
    var
      check :boolean;
      ercode: Integer;
      ermsg: string;
    
    Begin
    
     try
         if FService = Nil Then Begin
          FService := TLocalServiceConnection.Create;
          FService.StartService('serPublic');
          end;
      except
           Exit;
      end;
    //******************************************
    Цитата

    После клика на иконку идёт запрос на разрешение. 

    В манифесте только это. Что ему надо не понятно...

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

     

    PublicRadio.apk

  2. Огромное всем спасибо, что нашли время для тестирования!❤️

    И все же чувствуется, что надо что-то в манифесте добавить т.к. сказать укрепить его. :)

    Вот пользователь Олег Киреев с Android 10, говорит что приложение падает.

    И пользователь PowerOwl с Android 6.0.1 тоже.

    Может надо разбить надпись в манифесте: 

    <service android:exported="false" android:foregroundServiceType="mediaPlayback" android:name="com.embarcadero.services.serPublic" />

    на две штуки:

    <service  android:foregroundServiceType="mediaPlayback" />

    <service android:exported="false" android:name="com.embarcadero.services.serPublic" />

    или это бессмысленная манипуляция?

     

  3. Что-то забыла как правильно получить apk для магазина. Переключилась на Application Store далее Build All затем Deploy.

    На выходе получаю файл .aab

    Как получить .apk Где поставить галку в опциях проекта? Стоит false должен получиться apk, но не получается. Гугл у меня пока принимает apk без проблем.

    http://docwiki.embarcadero.com/RADStudio/Sydney/en/Deploying_Your_Signed_Android_Application

     

    apk.jpg

  4. Cпасибо. Удалось если вставлять в AndroidManifest.template.xml иначе все время генерирует в AndroidManifest.xml строку:

    <service android:exported="false" android:name="com.embarcadero.services.serPublic" />

    Убрано также firebase. Сейчас так:

    AndroidManifest.template.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!-- BEGIN_INCLUDE(manifest) -->
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="%package%"
            android:versionCode="%versionCode%"
            android:versionName="%versionName%"
            android:installLocation="%installLocation%">
    
        <uses-sdk android:minSdkVersion="%minSdkVersion%" android:targetSdkVersion="%targetSdkVersion%" />
        <%uses-permission%>
       
        <uses-feature android:glEsVersion="0x00020000" android:required="True"/>
        <application android:persistent="%persistent%" 
            android:restoreAnyVersion="%restoreAnyVersion%" 
            android:label="%label%" 
            android:debuggable="%debuggable%" 
            android:largeHeap="%largeHeap%"
            android:icon="%icon%"
            android:theme="%theme%"
            android:hardwareAccelerated="%hardwareAccelerated%"
            android:resizeableActivity="false"
            android:requestLegacyExternalStorage="true">
    
            <%provider%>
            <%application-meta-data%>
            <%uses-libraries%>
            
            <service android:exported="false" android:foregroundServiceType="mediaPlayback" android:name="com.embarcadero.services.serPublic" />
            
            <!-- Our activity is a subclass of the built-in NativeActivity framework class.
                 This will take care of integrating with our NDK code. -->
            <activity android:name="com.embarcadero.firemonkey.FMXNativeActivity"
                    android:label="%activityLabel%"
                    android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
                    android:launchMode="singleTask">
                <!-- Tell NativeActivity the name of our .so -->
                <meta-data android:name="android.app.lib_name"
                    android:value="%libNameValue%" />
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter> 
            </activity>
            <%activity%>
            <%receivers%>
        </application>
    </manifest>
    <!-- END_INCLUDE(manifest) -->

     

    AndroidManifest.xml в папке \Android64\Release

    <?xml version="1.0" encoding="utf-8"?>
    <!-- BEGIN_INCLUDE(manifest) -->
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.online.PublicRadio"
            android:versionCode="3"
            android:versionName="1.0.2"
            android:installLocation="auto">
    
        <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="29" />
        <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
        <uses-permission android:name="android.permission.INTERNET" />
    
       
        <uses-feature android:glEsVersion="0x00020000" android:required="True"/>
        <application android:persistent="False" 
            android:restoreAnyVersion="False" 
            android:label="PublicRadio" 
            android:debuggable="True" 
            android:largeHeap="False"
            android:icon="@drawable/ic_launcher"
            android:theme="@style/AppTheme"
            android:hardwareAccelerated="true"
            android:resizeableActivity="false"
            android:requestLegacyExternalStorage="true">
    
            
            
            
            
            <service android:exported="false" android:foregroundServiceType="mediaPlayback" android:name="com.embarcadero.services.serPublic" />
            
            <!-- Our activity is a subclass of the built-in NativeActivity framework class.
                 This will take care of integrating with our NDK code. -->
            <activity android:name="com.embarcadero.firemonkey.FMXNativeActivity"
                    android:label="PublicRadio"
                    android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
                    android:launchMode="singleTask">
                <!-- Tell NativeActivity the name of our .so -->
                <meta-data android:name="android.app.lib_name"
                    android:value="PublicRadio" />
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter> 
            </activity>
            
            <receiver android:name="com.embarcadero.rtl.notifications.NotificationAlarm" />
    
        </application>
    </manifest>
    <!-- END_INCLUDE(manifest) -->

     

    На Андроид 8.1 работает.

     

  5. Добавляем в  раздел <%services%> файла AndroidManifest.template.xml строки:
    <%services%>
            <service android:foregroundServiceType="mediaPlayback" />
            </service>
    //****************************************************************

    Получаем в файле AndroidManifest.xml:
     <service android:foregroundServiceType="mediaPlayback" />
            </service> //и тут ошибка строка №60 при попытки деплоя на телефон
    //**************************************************************** 

    [PAClient Error] Error: E2312 C:\Users\Lena\Documents\Embarcadero\Studio\Projects\delphi82\Android64\Release\PublicRadio\AndroidManifest.xml:60: error: Error parsing XML: mismatched tag

  6. foregroundServiceType должно быть цифра 2. Не пойму как правильно добавить Ваши рекомендации в манифестAndroidManifest.template.xml, подскажите.

    AndroidManifest.template.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!-- BEGIN_INCLUDE(manifest) -->
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="%package%"
            android:versionCode="%versionCode%"
            android:versionName="%versionName%"
            android:installLocation="%installLocation%">
    
        <uses-sdk android:minSdkVersion="%minSdkVersion%" android:targetSdkVersion="%targetSdkVersion%" />
        <%uses-permission%>
        <uses-feature android:glEsVersion="0x00020000" android:required="True"/>
        <application android:persistent="%persistent%" 
            android:restoreAnyVersion="%restoreAnyVersion%" 
            android:label="%label%" 
            android:debuggable="%debuggable%" 
            android:largeHeap="%largeHeap%"
            android:icon="%icon%"
            android:theme="%theme%"
            android:hardwareAccelerated="%hardwareAccelerated%"
            android:resizeableActivity="false"
            android:requestLegacyExternalStorage="true">
    
            <%provider%>
            <%application-meta-data%>
            <%uses-libraries%>
            <%services%>
            <!-- Our activity is a subclass of the built-in NativeActivity framework class.
                 This will take care of integrating with our NDK code. -->
            <activity android:name="com.embarcadero.firemonkey.FMXNativeActivity"
                    android:label="%activityLabel%"
                    android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
                    android:launchMode="singleTask">
                <!-- Tell NativeActivity the name of our .so -->
                <meta-data android:name="android.app.lib_name"
                    android:value="%libNameValue%" />
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter> 
            </activity>
            <%activity%>
            <%receivers%>
        </application>
    </manifest>
    <!-- END_INCLUDE(manifest) -->

    Сегодня сделано полный билд проекта и в файле AndroidManifest.xml появилось разрешение WAKE_LOCK, раньше его не было. Надо как-то убрать?

    <?xml version="1.0" encoding="utf-8"?>
    <!-- BEGIN_INCLUDE(manifest) -->
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.online.PublicRadio"
            android:versionCode="3"
            android:versionName="1.0.2"
            android:installLocation="auto">
    
        <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="29" />
        <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <permission android:name="com.online.PublicRadio.permission.C2D_MESSAGE" android:protectionLevel="signature" />
        <uses-permission android:name="com.online.PublicRadio.permission.C2D_MESSAGE" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    
        <uses-feature android:glEsVersion="0x00020000" android:required="True"/>
        <application android:persistent="False" 
            android:restoreAnyVersion="False" 
            android:label="PublicRadio" 
            android:debuggable="False" 
            android:largeHeap="False"
            android:icon="@drawable/ic_launcher"
            android:theme="@style/AppTheme"
            android:hardwareAccelerated="true"
            android:resizeableActivity="false"
            android:requestLegacyExternalStorage="true">
    
            <provider
                android:name="com.embarcadero.firebase.provider.FirebaseInitProvider"
                android:authorities="com.online.PublicRadio.firebaseinitprovider"
                android:exported="false"
                android:initOrder="100">
            </provider>
    
            <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_accent_color" />
            <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />
    
            
            <service android:exported="false" android:name="com.embarcadero.services.serPublic" />
    <service android:exported="false" android:name="com.embarcadero.firebase.messaging.ProxyFirebaseMessagingService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>
    
            <service android:exported="true" android:name="com.google.firebase.messaging.FirebaseMessagingService">
                <intent-filter android:priority="-500">
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>
    
            <service android:exported="false" android:name="com.google.firebase.components.ComponentDiscoveryService">
                <meta-data android:name="com.google.firebase.components:com.google.firebase.iid.Registrar" android:value="com.google.firebase.components.ComponentRegistrar" />
            </service>
    
    
            <!-- Our activity is a subclass of the built-in NativeActivity framework class.
                 This will take care of integrating with our NDK code. -->
            <activity android:name="com.embarcadero.firemonkey.FMXNativeActivity"
                    android:label="PublicRadio"
                    android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
                    android:launchMode="singleTask">
                <!-- Tell NativeActivity the name of our .so -->
                <meta-data android:name="android.app.lib_name"
                    android:value="PublicRadio" />
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter> 
            </activity>
            
            <receiver android:name="com.embarcadero.rtl.notifications.NotificationAlarm" />
            <receiver android:exported="true" android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:permission="com.google.android.c2dm.permission.SEND">
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                </intent-filter>
            </receiver>
    
        </application>
    </manifest>
    <!-- END_INCLUDE(manifest) -->

     

  7. Здравствуйте. Есть приложение музыкального плеера со службой переднего фона, которая позволяет проигрывать музыку даже если приложение свернуто. Без этой службы андроид убивает приложение через пару минут если оно свернуто. Приложение работает на андроид 7.1, 8.1 и 9. Других устройств для тестирования нет. На андроид 10 приложение при старте сразу падает. Возникла мысль, что андроид 10 не может запустить службу переднего плана. Код:

    procedure TForm1.FormCreate(Sender: TObject);
    Begin
    //Библиотека BASS для аудио http://www.un4seen.com/
     if not BASS_Init(-1, 44100, 0, nil, nil) Then Begin
    	   ShowMessage('Failed to initialize audio!' + sLineBreak + 'Не удалось инициализировать audio!');
         Exit;
         end;
    
     try
         if FService = Nil Then Begin
          FService := TLocalServiceConnection.Create;
          FService.StartService('serPublic');
          end;
      except
           Exit;
      end;

    Пользователь форума Tumaso, предложил код как отменить запуск службы для андроид 10. Лучше уж пусть приложение играет на переднем плане, чем просто падает при старте.

    uses
        ... Androidapi.JNI.Os, Androidapi.JNIBridge ...
    //изменения при страте в FormCreate
      if TJBuild_VERSION.JavaClass.SDK_INT <= 28 then
      begin
        try
          if not Assigned(FService) then
          begin
            FService := TLocalServiceConnection.Create;
            FService.StartService('serPublic');
          end;
        except
          // что нибудь делаем
        end;  
      end;

    Но возникает еще вопрос, а может для андроид 10 надо запросить какие-то дополнительные разрешения или что-то добавить в манифест? Сейчас из разрешений в опциях проекта стоит Foreground service и Internet. Устройства с андроид 10 у меня нет. Ниже код службы, за который меня не ругайте, это солянка найденная в интернете и этот код прекрасно работает на андроид 7.1, 8.1 и 9.

    unit Unit1;
    
    interface
    
    uses
      System.SysUtils,
      System.Classes,
      System.Android.Service,
      AndroidApi.JNI.GraphicsContentViewText,
      Androidapi.JNI.Os,
      Androidapi.JNI.App,
      Androidapi.JNI.Support,
      Androidapi.JNI.JavaTypes,
      Androidapi.Helpers,
      Androidapi.JNIBridge,
      Androidapi.Jni,
      System.Notification;
    
    type
      TDM = class(TAndroidService)
        NotificationCenter1: TNotificationCenter;
        function AndroidServiceStartCommand(const Sender: TObject;
          const Intent: JIntent; Flags, StartId: Integer): Integer;
    
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      DM: TDM;
    
    implementation
    
    {%CLASSGROUP 'FMX.Controls.TControl'}
    
    {$R *.dfm}
    
    
    
    function TDM.AndroidServiceStartCommand(const Sender: TObject;
      const Intent: JIntent; Flags, StartId: Integer): Integer;
    
    var
      //Android 8.1, 9
      ServiceChannel: JNotificationChannel;
      NotificationManager: JNotificationManager;
      Obj: JObject;
      NewIntent: JIntent;
      ncb: JNotificationCompat_Builder;
      ntf: JNotification;
      PendingIntent: JPendingIntent;
      //Android 7.1
      service             : JService;
      serviceObjectId     : Pointer;
      ntf2                : JNotification;
      intent2             : JIntent;
      PendingIntent2      : JPendingIntent;
    
    begin
    
       Result := TJService.JavaClass.START_NOT_STICKY;
    
       // can't ref .O on earlier phones, must hardcode
      if TJBuild_VERSION.JavaClass.SDK_INT > 26 then // JBuild_VERSION_CODES.JavaClass.O
      begin
         //Android 8.1
         //new ways for SDK > 26 (won't be called when API < 26 anyways)
         try
    
          ServiceChannel := TJNotificationChannel.JavaClass.init(
          StringtoJString('com.radio.one'), //CHANNEL_ID
          StrToJCharSequence('Public radio Channel'),
          TJNotificationManager.JavaClass.IMPORTANCE_DEFAULT
        );
    
        Obj := TAndroidHelper.Context.getSystemService(
        TJContext.JavaClass.NOTIFICATION_SERVICE);
        NotificationManager := TJNotificationManager.Wrap(Obj);
        NotificationManager.createNotificationChannel(ServiceChannel);
    
        NewIntent:= TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(
          TAndroidHelper.Context.getPackageName());
        NewIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
        NewIntent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER);
        NewIntent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
    
        PendingIntent := TJPendingIntent.JavaClass.getActivity(
          TAndroidHelper.Context, 0, NewIntent,
          TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK
        );
    
        ncb := TJNotificationCompat_Builder.JavaClass.init(
          TAndroidHelper.Context,
          StringToJString('com.radio.one')
        );
    
       ncb.setContentTitle(StrToJCharSequence('PublicRadio Service'));
       // ncb.setTicker(StrToJCharSequence('MyCommsService')); // can't remember why this is commented out to be honest
       ncb.setSmallIcon(JavaService.getApplicationInfo.icon);
       ncb.setContentIntent(PendingIntent);
       ncb.setOngoing(True);
       ntf := ncb.build;
       JavaService.startForeground(StartId, ntf);
       except
           exit;
       end;
    
     end
     else
     begin
          //Android 7.1
         try
          serviceObjectId  := (JavaService as ILocalObject).GetObjectID;
          service          := TJService.Wrap(serviceObjectId);
          /////ntf2             := TJNotification.Create;
          ////ntf2.icon        := service.getApplicationInfo.icon;
    
        NewIntent:= TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(
          TAndroidHelper.Context.getPackageName());
        NewIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
        NewIntent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER);
        NewIntent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
    
        PendingIntent2 := TJPendingIntent.JavaClass.getActivity(
          TAndroidHelper.Context, 0, NewIntent,
          TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK
        );
    
          ncb := TJNotificationCompat_Builder.JavaClass.init(
          TAndroidHelper.Context,
          StringToJString('com.radio.one')
        );
    
          //intent2  := TJIntent.Create;
          //PendingIntent2 := TJPendingIntent.JavaClass.getActivity(service.getApplicationContext, 0, intent2, 0);
    
          ncb.setContentTitle(StrToJCharSequence('PublicRadio'));
          // ncb.setTicker(StrToJCharSequence('MyCommsService'));
          ncb.setSmallIcon(JavaService.getApplicationInfo.icon);
          ncb.setContentIntent(PendingIntent2);
          ncb.setOngoing(True);
          ntf2 := ncb.build;
    
          ntf2.setLatestEventInfo(service.getApplicationContext, StrToJCharSequence('PublicRadio'), StrToJCharSequence('PublicRadio Service'), PendingIntent2);
          service.startForeground(StartId, ntf2);
       except
           exit;
       end;
    
      end;
    
    end;
    
    end.

     

  8. Что-то не получается. С паскалем у меня пока не очень... У меня есть код который должен выполняться только если версия андроид равно 9 или ниже. Дело в том, что на 10 андроиде приложение сразу падает. Видимо не хочет запускать службу. Проверить возможности в отладке нет, из-за отсутствия устройства с андроид 10. Поэтому пытаюсь не запускать службу на андроид 10 и выше.

    //FormCreate 
     try
         if FService = Nil Then Begin
            FService := TLocalServiceConnection.Create;
            FService.StartService('serPublic');
          end;
      except
           Exit;
      end;

    Пытаюсь обрамить этот код условием:

    if TJBuild_VERSION.JavaClass.SDK_INT <= 28 then

    Подчеркивает красным TJBuild_VERSION. Я так понимаю надо что-то добавить в uses.

    Подскажите, пожалуйста, как правильно обрамить этот код условием if TJBuild_VERSION.JavaClass.SDK_INT <= 28 

    Спасибо.

  9. Здравствуйте.

    Не могу разобраться с TWebBrowser на андроиде. TWebBrowser упорно грузит старый вариант страницы. Ввожу ссылку в Хроме - все нормально, вижу новый вариант страницы. Выгружаю программу полностью из памяти. Компилирую. Запускается по новой на устройстве и вижу старый вариант страницы. Пробую создать TWebBrowser динамически, не помогает, показывает старый первый вариант страницы. RAD10.4.1. Clean проекта не помогло. Подскажите, что не так? Спасибо.

    procedure TForm2.FormShow(Sender: TObject);
    var
      WebBrowser: TWebBrowser;
    begin
      WebBrowser := TWebBrowser.Create(Self);
      WebBrowser.Parent := Self;
      WebBrowser.Align := TAlignLayout.Client;
    
    //упорно отображает старый вариант страницы, а в хроме или опере все нормально
      WebBrowser.Navigate('http://91.199.194.34/radionews.html');
    
    end;

     

  10. Прошу прощения исправлено. Забыла что для новых версий надо импортировать google-services.json из коносли firebase

    Ошибка пропала, однако токен устройства пустой.

    В манифесте из статьи

    https://fire-monkey.ru/topic/3840-статья-настройка-пуш-уведомлении-через-сервис-firebase-для-android-и-ios-часть-2/

    указано

            <%receivers%>
            <service android:name="com.embarcadero.gcm.notifications.GCMIntentService" />

    В опциях проекта api key указан. true в опциях проекта Entitlement List-> Receve push notifications указано

    Из консоли firebse взят Sender ID

    const
      FAndroidServerKey = '1036128679228';

    Но не выходит каменный цветок. :)

    Цитата

    procedure TForm1.PushServiceRegister;
    begin

      if CheckInet() then begin

      FPushService := nil;
      FPushServiceConnection := nil;

      FPushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.FCM);


      if Assigned(FPushService) then begin
        FPushService.AppProps[TPushService.TAppPropNames.GCMAppID] := FAndroidServerKey;
      end;


      if Assigned(FPushService) then
      begin
        FPushServiceConnection := TPushServiceConnection.Create(FPushService);
        FPushServiceConnection.Active := true;
        FPushServiceConnection.OnChange := OnServiceConnectionChange;
        FPushServiceConnection.OnReceiveNotification := OnReceiveNotificationEvent;

        FDeviceID := FPushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
        FDeviceToken := FPushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
        ShowMessage('Вижу что пусто: ' + FDeviceToken);//FDeviceID есть
        // тут отправляем в хранилище токенов (на сервер с БД например)
        if(Trim(FDeviceID) <> EmptyStr) and (Trim(FDeviceToken) <> EmptyStr) then
        begin
                   

              RegisterDevice();

        end;

      end;

     end;

    end;

    Это не помогло пустой токен

    http://fire-monkey.ru/topic/4839-fpushservicedevicetokenvalue-nil-что-делать/?page=3#comment-32995

     

  11. Здравствуйте.

    Создано приложение для получения пушей. Материалы отсюда:

    https://fire-monkey.ru/topic/3840-статья-настройка-пуш-уведомлении-через-сервис-firebase-для-android-и-ios-часть-2/

    Отсюда стало понятно что для 10.4.1 надо сделать изменение:

    http://docwiki.embarcadero.com/RADStudio/Sydney/en/Firebase_Android_Support

    TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.FCM);

    Однако при старте приложения сыпались ошибки:

    java.lang.RuntimeException: Unable to get provider com.embarcadero.firebase.provider.FirebaseInitProvider: java.lang.IllegalStateException: ApplicationId must be set.

    at android.app.ActivityThread.installProvider(ActivityThread.java:6398) и т.д.

    При полностью закоментированном коде ошибка не пропадала.

    Выяснилось, что ошибка возникает если установить в true в опциях проекта Entitlement List-> Receve push notifications тогда ошибка. Снять галочку ошибки нет.

    Кому либо удалось сделать приложение с поддержкой пушей в 10.4.1?

    Для 10.3.1 был какой-то патч:

    https://blog.marcocantu.com/blog/2019-05-android-firebase-patch-blog.html

    Но у меня 10.4.1

    Спасибо.

     

     

     

     

  12. В 10.12.2020 в 16:22, Android сказал:

    keystore в настройках проекта указали?

    Да.

    Причина найдена. Скорее всего это ошибка эмбаркадеро. Не дружит этот проект с внутренностями IDE.

    Если в опциях проекта снять галочку Generate Android App Bundle file (arm + arm64) то нормально компилируется и в режиме Development и в Application Store.

    При установленной галочке нормально только в режиме Development.

    Придется публиковать только для Андроид 6+...

  13. Здравствуйте.

    В проекте используется библиотека BASS для воспроизведения звука. Проект Андроид Дельфи 10.3 / 10.4.1

    В режиме Development все работает и компилируеться нормально. Ошибок нет.

    При переключении в режим Application Store при попытке Build возникает ошибка:

    [DCC Error] E2597 C:\Users\Public\Documents\Embarcadero\Studio\20.0\PlatformSDKs\android-ndk-r17b\toolchains\arm-linux-androideabi-4.9\prebuilt\windows\bin\arm-linux-androideabi-ld.exe: cannot find -lbass
    [DCC Fatal Error] F2588 Linker error code: 1 ($00000001)

    Все пути прописаны. Ничего не менялось. Однако в Development режиме все нормально, а в Application Store ошибка. Что может быть упущено для Application Store?

    Спасибо.

    error.jpg

  14. Код ниже отрабатывает как надо. Проверено в Андроид 7.1 и Андроид 8.1. Других телефонов нет.  Может кому пригодиться код  для службы переднего плана.

    Код скомбинирован из этого источника: Foreground Service

    function TDM.AndroidServiceStartCommand(const Sender: TObject;
      const Intent: JIntent; Flags, StartId: Integer): Integer;
    var
      //Android 8.1
      ServiceChannel: JNotificationChannel;
      NotificationManager: JNotificationManager;
      Obj: JObject;
      NewIntent: JIntent;
      ncb: JNotificationCompat_Builder;
      ntf: JNotification;
      PendingIntent: JPendingIntent;
      //Android 7.1
      service             : JService;
      serviceObjectId     : Pointer;
      ntf2                : JNotification;
      intent2             : JIntent;
      PendingIntent2      : JPendingIntent;
    
    begin
    
       Result := TJService.JavaClass.START_NOT_STICKY;
    
       // can't ref .O on earlier phones, must hardcode
      if TJBuild_VERSION.JavaClass.SDK_INT > 26 then // JBuild_VERSION_CODES.JavaClass.O
      begin
         //Android 8.1
         //new ways for SDK > 26 (won't be called when API < 26 anyways)
          ServiceChannel := TJNotificationChannel.JavaClass.init(
          StringtoJString('com.radio.one'), //CHANNEL_ID
          StrToJCharSequence('Public radio Channel'),
          TJNotificationManager.JavaClass.IMPORTANCE_DEFAULT
        );
    
        Obj := TAndroidHelper.Context.getSystemService(
        TJContext.JavaClass.NOTIFICATION_SERVICE);
        NotificationManager := TJNotificationManager.Wrap(Obj);
        NotificationManager.createNotificationChannel(ServiceChannel);
    
        NewIntent:= TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(
          TAndroidHelper.Context.getPackageName());
        NewIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
        NewIntent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER);
        NewIntent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
    
        PendingIntent := TJPendingIntent.JavaClass.getActivity(
          TAndroidHelper.Context, 0, NewIntent,
          TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK
        );
    
        ncb := TJNotificationCompat_Builder.JavaClass.init(
          TAndroidHelper.Context,
          StringToJString('com.radio.one')
        );
    
       ncb.setContentTitle(StrToJCharSequence('PublicRadio Service'));
       // ncb.setTicker(StrToJCharSequence('MyCommsService')); // can't remember why this is commented out to be honest
       ncb.setSmallIcon(JavaService.getApplicationInfo.icon);
       ncb.setContentIntent(PendingIntent);
       ncb.setOngoing(True);
       ntf := ncb.build;
       JavaService.startForeground(StartId, ntf);
    
     end
     else
     begin
          //Android 7.1
          serviceObjectId  := (JavaService as ILocalObject).GetObjectID;
          service          := TJService.Wrap(serviceObjectId);
          /////ntf2             := TJNotification.Create;
          ////ntf2.icon        := service.getApplicationInfo.icon;
    
        NewIntent:= TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(
          TAndroidHelper.Context.getPackageName());
        NewIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
        NewIntent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER);
        NewIntent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
    
        PendingIntent2 := TJPendingIntent.JavaClass.getActivity(
          TAndroidHelper.Context, 0, NewIntent,
          TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK
        );
    
          ncb := TJNotificationCompat_Builder.JavaClass.init(
          TAndroidHelper.Context,
          StringToJString('com.radio.one')
        );
    
          //intent2  := TJIntent.Create;
          //PendingIntent2 := TJPendingIntent.JavaClass.getActivity(service.getApplicationContext, 0, intent2, 0);
    
          ncb.setContentTitle(StrToJCharSequence('PublicRadio'));
          // ncb.setTicker(StrToJCharSequence('MyCommsService'));
          ncb.setSmallIcon(JavaService.getApplicationInfo.icon);
          ncb.setContentIntent(PendingIntent2);
          ncb.setOngoing(True);
          ntf2 := ncb.build;
    
          ntf2.setLatestEventInfo(service.getApplicationContext, StrToJCharSequence('PublicRadio'), StrToJCharSequence('PublicRadio Service'), PendingIntent2);
          service.startForeground(StartId, ntf2);
      end;
    
    end;

    Разрешение Foreground service=true 

    В манифесте:

     <service android:exported="false" android:name="com.embarcadero.services.serPublic" />

    Старт службы:

    private
        { Private declarations }
         FService: TLocalServiceConnection;
    
    //*****************************************
    
    if FService = Nil Then Begin
      FService := TLocalServiceConnection.Create;
      FService.StartService('serPublic');
      end;

    Проверено в Дельфи 10.3 и Дельфи 10.4.1

  15. Это вариант работает для Андроид 8.1. С Андроид 7 падает после слеша. Видимо для Android 7.0 чего-то не хватает...

    function TDM.AndroidServiceStartCommand(const Sender: TObject;
      const Intent: JIntent; Flags, StartId: Integer): Integer;
    var
      ServiceChannel: JNotificationChannel;
      NotificationManager: JNotificationManager;
      Obj: JObject;
      NewIntent: JIntent;
      ncb: JNotificationCompat_Builder;
      ntf: JNotification;
      PendingIntent: JPendingIntent;
    begin
    
      Result := TJService.JavaClass.START_NOT_STICKY;
    
       ServiceChannel := TJNotificationChannel.JavaClass.init(
          StringtoJString('com.radio.one'),
          StrToJCharSequence('Public radio Channel'),
          TJNotificationManager.JavaClass.IMPORTANCE_DEFAULT
          );
        Obj := TAndroidHelper.Context.getSystemService(
          TJContext.JavaClass.NOTIFICATION_SERVICE);
        NotificationManager := TJNotificationManager.Wrap(Obj);
        NotificationManager.createNotificationChannel(ServiceChannel);
        PendingIntent := TJPendingIntent.JavaClass.getActivity(
          JavaService.getApplicationContext, 0, Intent, 0
          );
        ncb := TJNotificationCompat_Builder.JavaClass.init(
          TAndroidHelper.Context,
          StringToJString('com.radio.one')
          );
        ncb.setContentTitle(StrToJCharSequence('PublicRadio'));
        // ncb.setTicker(StrToJCharSequence('Communications Service'));
        ncb.setSmallIcon(JavaService.getApplicationInfo.icon);
        ncb.setContentIntent(PendingIntent);
        ncb.setOngoing(True);
        ntf := ncb.build;
        JavaService.startForeground(StartId, ntf);
    
    end;

     

×
×
  • Создать...