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

OnePeople

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

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

  • Посещение

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

    57

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

  1. С радостью бы помог, и скорее всего если не сможете сделать то помогу, но только ближе к ноябрю((( 

    Только закончил с поисками и реализацией отловки AudioFocus, наконец то)))))))))

    У самого музыка пока не в сервисе, но я думаю как то так, без 

    AndroidServiceUnBind
    

     

    function TCronysDM.AndroidServiceStartCommand(const Sender: TObject;
      const Intent: JIntent; Flags, StartId: Integer): Integer;
    Var
      Action: string;
    begin
      Action := JStringToString(Intent.getAction);
      if Action = 'StartService' then
      begin

      BASS_Init(-1, 44100, 0, nil, nil); //инициализация bass
      BASS_StreamFree(str);
      str := BASS_StreamCreateURL(PChar('http://91.199.194.34:8000'), 0, BASS_UNICODE, nil, nil);
      //ShowMessage(IntToStr(BASS_ErrorGetCode));
    
    
      If BASS_ErrorGetCode = 0 Then
      Begin
         BASS_ChannelPlay(str, True); //начать воспроизведение
       End;

      end;

      if Action = 'StopService' then
      begin

      BASS_ChannelStop(str); //остановить воспроизведение
      BASS_StreamFree(str);
    

        JavaService.stopSelf;
        result := TJService.JavaClass.START_NOT_STICKY; // don't reload service
        exit;
      end;

      result := TJService.JavaClass.START_STICKY; // rerun service if host app stops
    end;

     

     

    запуск сервиса

            FService := TJIntent.Create;
            FService.setClassName(TAndroidHelper.Context.getPackageName(),
            TAndroidHelper.StringToJString('com.embarcadero.services.cronysrv'));
            FService.setAction(StringToJString('StartService'));
            TAndroidHelper.Activity.startService(FService);

     

    По вышему коду при убийстве приложения, убивается и сервис???? Это вопрос

  2. 58 минут назад, Ingalime сказал:

     Вывод один: с игрой музыки в фоне можно попрощаться.?

    Создайте сервис в нем код из вашего приложения по запуску воспроизведения

    А в приложении, делайте отправку broadcast сообщений о старте или остановки проигрывания

    В этом радио так и сделано! 

     

    И нотификейшен с кнопками тоже можно на делфи сделать!

  3. Делал тут темы для своего приложения (лаунчера) и встал вопрос об открытии файла темы из проводника. И конечно же уперся в то что intent возвращает всегда один и тот же как при открытии программы.

    Итого поздно)), но может кому пригодится 

     <intent-filter>
                  <action android:name="android.intent.action.VIEW"/>
             	<action android:name="android.intent.action.EDIT"/>
                  <category android:name="android.intent.category.DEFAULT"/>
                  <category android:name="android.intent.category.BROWSABLE"/>
                    <data android:scheme="file" />
    		<data android:scheme="content" />
    		<data android:scheme="http" />
    		<data android:scheme="https" />
    		<data android:host="*" />             
                    <data android:pathPattern=".*\\.caskin" />
                </intent-filter>
                <intent-filter>
                  <action android:name="android.intent.action.VIEW"/>
    	      <action android:name="android.intent.action.EDIT"/>
                  <category android:name="android.intent.category.DEFAULT"/>
                  <category android:name="android.intent.category.BROWSABLE"/>
                    <data android:scheme="file" />
    		<data android:scheme="content" />
    		<data android:scheme="http" />
    		<data android:scheme="https" />
    		<data android:host="*" />
                    <data android:mimeType="*/*" /> 
    		<data android:pathPattern=".*\\.caskin" />
            
                </intent-filter>
    
    
    
    
    
    private
        var IMessageSubscriptionID: Integer;
        procedure HandleIntentMessage(const Sender: TObject; const M: TMessage);
        function OnNewIntent(Intent: JIntent): Boolean;
    
    
    procedure TForm1.FormCreate(Sender: TObject);
    var
     aFMXApplicationEventService: IFMXApplicationEventService;
    begin
        if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(aFMXApplicationEventService)) then
           aFMXApplicationEventService.SetApplicationEventHandler(HandleAppEvent);
    
    	MainActivity.registerIntentAction(TJIntent.JavaClass.ACTION_VIEW);
        IMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage(
        TMessageReceivedNotification, HandleIntentMessage);
    end;
    
    function TForm1.OnNewIntent(Intent: JIntent): Boolean;
    var
      fPath: String;
    begin
      Result := False;
      if Intent <> nil then
      begin
       fPath:=  Intent.getData.getEncodedPath;
      end;
    end;
    
    
    procedure TForm1.HandleActivityMessage(const Sender: TObject; const M: TMessage);
    begin
      if M is TMessageResultNotification then
        OnActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode,
          TMessageResultNotification(M).Value);
    end;
    
    
    function TForm1.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
    var
    myIntent: JIntent;
    insSkinPath: String;
    begin
      case AAppEvent of
        TApplicationEvent.FinishedLaunching:
        begin
        try
         myIntent := MainActivity.getIntent;
        if myIntent <> nil then
          OnNewIntent(myIntent);
           except
           end;
        end;
    
      end;
    
      Result := True;
    
    end;

     

  4. Поздно, но может кому пригодится

    function TForm1.Blur(sbit: TBitmap): TBitmap;
    var
      FilterClass: TFilterClass;
      FFilter: TFilter;
      FFilterParams: TFilterRec;
      BitmSource, BitmDest: TBitmap;
    begin
          BitmSource:=TBitmap.Create;
          BitmSource.Assign(sbit);
          Result:=TBitmap.Create;
          FFilter := TFilterManager.FilterByName('GaussianBlur');
          FilterClass := TFilterManager.FilterClassByName('GaussianBlur');
          FFilterParams := FilterClass.FilterAttr;
          FFilter.ValuesAsFloat['BlurAmount']:=5.7;
          FFilter.Apply;
          FFilter.ValuesAsBitmap['Input'] := BitmSource;
          Result.Assign(FFilter.ValuesAsBitmap['output']);
          FreeAndNil(FFilter);
          FreeAndNil(BitmSource);
    end;
    
    function TForm1.Tint(sbit: TBitmap; tintColor: TAlphaColor): TBitmap;
    var
      FilterClass: TFilterClass;
      FFilter: TFilter;
      FFilterParams: TFilterRec;
      BitmSource, BitmDest: TBitmap;
    begin
          BitmSource:=TBitmap.Create;
          BitmSource.Assign(sbit);
          Result:=TBitmap.Create;
          FFilter := TFilterManager.FilterByName('FillRGB');
          FilterClass := TFilterManager.FilterClassByName('FillRGB');
          FFilterParams := FilterClass.FilterAttr;
          FFilter.ValuesAsColor['Color']:=tintColor;
          FFilter.Apply;
          FFilter.ValuesAsBitmap['Input'] := BitmSource;
    
    
          Result.Assign(FFilter.ValuesAsBitmap['output']);
          FreeAndNil(FFilter);
          FreeAndNil(BitmSource);
    end;

     

  5. Вопрос решен, дело было в классе drawable, существует не только bitmapdrawable, но и adaptiveicon и извлекать ее нужно по своему, причем все время до сегодняшнего дня стоял костыль, а тут в другом месте, опять, при извлечении иконки стало приложение падать и как оказалось хорошо, что стало падать, решение помогло убить двух зайцев одним махом)))

  6. Если платформа Android:

    1. listbox тормознутый вариант, но да ооочень простой и удобный

    2. Alcinoe - набор примитивов которым можно программно сделать любой список, скорость отрисовки бомбическая, косяк в том что создаются компоненты долговато, нужна грамотная реализация подрузки данных и создания компонентов, но по мне это лучший вариант для горизонтального списка.

    3. ListView если список вертикальный то самое оно для вас, единственное с выравниванием и динамической высотой поработать нужно будет, но код есть в сети.

     

  7. Пробую отловить AudioFocus так (нашел на просторах интернета)

    Спойлер

     

    type
      TAudioFocusChangeEvent = procedure(focusChange: Integer) of object;

      TMyAudioFocusChangeListener = class(TJavaLocal, JAudioManager_OnAudioFocusChangeListener)
        private
        FParent : TForm1;
        FOnAudioFocusChanged: TAudioFocusChangeEvent;
      public
        procedure onAudioFocusChange(focusChange: Integer); cdecl;
        property OnAudioFocusChanged: TAudioFocusChangeEvent read FOnAudioFocusChanged
    write FOnAudioFocusChanged;
       end;

    .....

    procedure TMyAudioFocusChangeListener.onAudioFocusChange(focusChange: Integer);
    begin
      if Assigned(FOnAudioFocusChanged) then
        begin
          FOnAudioFocusChanged(focusChange);
          Form1.Memo2.Lines.Add(focusChange.ToString);
        end;
    end;

     

    Безрезультатно(

     

     

     

  8. Вот статья с инструкцией, по созданию сервиса

    https://stackoverflow.com/questions/27962192/is-it-possible-to-read-the-notifications-of-other-applications-on-android-with-d

    Единственное я удалил с исходника сервиса, все что связанно с 

    import android.support.v4.content.LocalBroadcastManager;
    

    и использовал обычный BroadcastReciver 

    Спойлер

    package com.embarcadero.ИМЯ ВАШЕГО СЕРВИСА;

    import android.content.Context;
    import android.content.Intent;
    import android.content.BroadcastReceiver;
    import android.os.Bundle;
    import android.service.notification.NotificationListenerService;
    import android.service.notification.StatusBarNotification;
    import android.util.Log;


    public class NotificationService extends NotificationListenerService {

        static final String TAG = "NotificationService";

        Context context;

        @Override
        public void onCreate() {
            super.onCreate();
            context = getApplicationContext();
            Log.d(TAG,"Service has been started!");
        }
        @Override

        public void onNotificationPosted(StatusBarNotification sbn) {
        Log.d(TAG,"Notification Posted!");
            String pack = sbn.getPackageName();
            Bundle extras = sbn.getNotification().extras;
            String title = extras.getString("android.title");
            String text = extras.getCharSequence("android.text").toString();
            String id = sbn.getTag();
            Integer im = extras.getInt("android.icon");

            Log.i("Package", pack);
            Log.i("Title",title);
            Log.i("Text",text);
            if (id != null){
                Log.i("Key", id);
            }
            Intent msgrcv = new Intent("Msg");
            msgrcv.putExtra("package", pack);
        msgrcv.putExtra("status", "posted");
            msgrcv.putExtra("key", id);
            msgrcv.putExtra("title", title);
            msgrcv.putExtra("text", text);
        msgrcv.putExtra("icon", im.toString());
            sendBroadcast(msgrcv);

        }

        @Override

        public void onNotificationRemoved(StatusBarNotification sbn) {
            Log.d(TAG,"Notification Removed");
        String pack = sbn.getPackageName();
            Intent msgrcv = new Intent("Msg");
            msgrcv.putExtra("package", pack);
        msgrcv.putExtra("status", "removed");
            sendBroadcast(msgrcv);
        }
    }

    Далее даем разрешение

    BIND NOTIFICATION LISTENER SERVICE

    В манифесте после строки  <%services%> дописываем

     <service android:name="com.embarcadero.ИМЯ ВАШЕГО СЕРВИСА.NotificationService"
          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
         <intent-filter>
             <action android:name="android.service.notification.NotificationListenerService" />
         </intent-filter>
     </service>

    Иконку доставать так

                  iconapp:=TBitmap.Create;
                  Surface := TBitmapSurface.Create;    
                  NotifyDraw:=TAndroidHelper.Context.createPackageContext(stpackage, 0).getResources.getDrawableForDensity(idicon, 480);
                    if StrToInt(NotifyDraw.getAlpha.ToString)=255 then
                        Bitmap := TJBitmapDrawable.Wrap((NotifyDraw.getCurrent as ILocalObject).GetObjectID).getBitmap;
                    if Bitmap<>nil then
                        begin
                          JBitmapToSurface(Bitmap, Surface);
                          iconapp.Assign(Surface);
                        end;

     

  9. Всем привет! Подскажите пожалуйста как это заставить работать на Delphi (Rad Studio 10.3.3)

    Можно класс как то из это создать?

    Хоть в какую сторону копать, желательно мини пример!

    
    
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.service.notification.NotificationListenerService;
    import android.service.notification.StatusBarNotification;
    import android.util.Log;
    import android.support.v4.content.LocalBroadcastManager;
    
    
    public class NotificationService extends NotificationListenerService {
    
        static final String TAG = "NotificationService";
    
        Context context;
    
        @Override
        public void onCreate() {
            super.onCreate();
            context = getApplicationContext();
            Log.d(TAG,"Service has been started!");
        }
        @Override
    
        public void onNotificationPosted(StatusBarNotification sbn) {
        Log.d(TAG,"Notification Posted!");
            String pack = sbn.getPackageName();
            Bundle extras = sbn.getNotification().extras;
            String title = extras.getString("android.title");
            String text = extras.getCharSequence("android.text").toString();
            String id = sbn.getTag();
    
            Log.i("Package", pack);
            Log.i("Title",title);
            Log.i("Text",text);
            if (id != null){
                Log.i("Key", id);
            }
            Intent msgrcv = new Intent("Msg");
            msgrcv.putExtra("package", pack);
            msgrcv.putExtra("key", id);
            msgrcv.putExtra("title", title);
            msgrcv.putExtra("text", text);
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
    
        }
    
        @Override
    
        public void onNotificationRemoved(StatusBarNotification sbn) {
            Log.d(TAG,"Notification Removed");
    
        }
    }
  10. 21 час назад, Алексей Данильченко сказал:


      lIntent.setType(StringToJString('vnd.android.cursor.dir/email'));

    Но стоит только прикрепить только что сгенерированый Excel файл и приложение GMail говорит, что Не удалось прикрепить файл. Помогите побороть.

    Я думаю здесь тип файла должен быть или нет?

  11. 33 минуты назад, x11 сказал:

    Ок, замурчательно.

    А что там такого в манифесте прописано? Может там указано, что твоё приложение - для Андроид 4?

    Просто подобные приложения в Маркете не опубликуешь.

    А какой смысл перехват номеров в постоянно запущенном приложении? Оно же не будет у тебя постоянно на переднем плане, как только ты откроешь другое приложение, Андроид твое приложение через какое-то время прикроет все равно и оно не будет перехватывать номера.

    До маркета ещё далеко. 

    Да ни какого, потом все перенесется в сервис.

    А есть пример с окном SYSTEM ALERT???

    private void showWindow(Context context, String phone) {
       windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
       LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
       WindowManager.LayoutParams params = new WindowManager.LayoutParams(
               WindowManager.LayoutParams.MATCH_PARENT,
               WindowManager.LayoutParams.WRAP_CONTENT,
               WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
               WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
               PixelFormat.TRANSLUCENT);
       params.gravity = Gravity.TOP;
    
       windowLayout = (ViewGroup) layoutInflater.inflate(R.layout.info, null);
    
       TextView textViewNumber=(TextView) windowLayout.findViewById(R.id.textViewNumber);
       Button buttonClose=(Button) windowLayout.findViewById(R.id.buttonClose);
       textViewNumber.setText(phone);
       buttonClose.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               closeWindow();
           }
       });
    
       windowManager.addView(windowLayout, params);
    }

     

    AndroidManifest.rar

  12. В 30.01.2020 в 02:22, x11 сказал:

    Ты мой пример использовал из первого сообщения?

    На какой версии Дельфи собран проект и на какой версии Андроида запустил? Меня ли что-то в манифесте?

    10.3.3 community

    Андроид 8

    Манифест свой, приложение без сервиса.

     

  13. Rad Studio 10.3.3

    Android 64bit

    Делаю загрузку списка приложений, всё работает на телефоне, как только запускаю на целевом устройстве (андроид магнитола), то падает на этой строке

     Bitmap := TJBitmapDrawable.Wrap((Drawable as ILocalObject).GetObjectID).getBitmap;

    причем только на некоторых приложениях, например у меня идет календарь, всё нормально иконка добавляется, затем chrome падает на этой строке, затем email тоже нормально отрабатывает функция

    КАК ТАК ТО

    Уже все перепробывал, может кто знает другой метод получения иконки приложения, пользуюсь этим

       Drawable := LApplicationInfo.loadIcon(TAndroidHelper.Context.getPackageManager);
                          if Assigned(Drawable)  then
                          Bitmap := TJBitmapDrawable.Wrap((Drawable as ILocalObject).GetObjectID).getBitmap;
    
                       if Assigned(Bitmap) then
                        begin
    
                          JBitmapToSurface(Bitmap, Surface);
                          iconapp.Assign(Surface);
                        end;

     

  14. Всем привет. Rad studio 10.3.3

    Кто нибудь знает как работать с Bluetooth PBAP?

    Мои мысли в грубой форме

    Спойлер

     

      FAdapter := FBluetoothManager.CurrentAdapter;

    FBluetoothManager.StartDiscovery(10000);

    OnDiscoveryEnd   -> for I := 0 to ADevices.Count - 1 do

     FAdapter.Pair()

     FSocket := LDevice.CreateClientSocket(StringToGUID(ServiceGUI), False);   где ServiceGUI = {0000112E-0000-1000-8000-00805F9B34FB}

        ToSend := TEncoding.UTF8.GetBytes( ЗАПРОС);
        FSocket.SendData(ToSend);

     

    Вопросы:

    1.Какой запрос мне отправить, чтобы получить телефонную книгу другого устройства?

    2.Чтобы потом позвонить, мне нужно будет еще один сокет создавать, с подключением к другому сервису?

    PS Спасибо тем кто откликнется!

    Может кто в java шарит

    https://github.com/gitzxon/MyBluetoothDemo/blob/master/app/src/main/java/android/bluetooth/client/pbap/BluetoothPbapClient.java

     

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