Pular para o conteúdo principal

Google Analytics in Delphi Mobile Without 3rd party Components


Google Analytics in Delphi Mobile Without 3rd party Components

Google analytics is the most exciting tool to have in your Swiss knife. With it you can have a nice picture of what is going on in your mobile apps, how users are using it, which time of the day it is most used and much more. And everything in REAL TIME!

With a little dig into Google Analytics API I realized that anybody can add such a valuable tool in any mobile app in 30 minutes. But 30 minutes is too much nowadays, so, here are the steps for you to achieve it in 5 minutes:

1- Make sure the google-analytics jar is in your project libraries and it is enabled:


2- Create a Data Module with these methods/events (*described in analytics unit, below). I've created some consts that organizes the events and actions in dimensions, so you can group that information for statistics purposes. I created 3 dimensions: one for exceptions, one for events and one for actions of the user.

3- Call AppAnalytics.Add to register any exception, event  or user action. For example, if the user clicks a menu item to share your app, you woul make a call like this:

procedure TfrmAppOfertasDoDia.lbShareClick(Sender: TObject);
begin
  AppAnalytics.Add(DIM_ACTION, AC_SHAREAPP);
  //app code continues here
end;

//Complete DataModule unit that holds analytics methods
//
unit dAnalytics;
interface
uses
  System.SysUtils, System.Classes, System.IOUtils
  {$IFDEF ANDROID}
  , Androidapi.JNI.JavaTypes
  , Androidapi.JNI.Analytics
  , Androidapi.Helpers
  {$ENDIF}
  ;
const
  //Analytics dimension
  DIM_EXCEPT       = 'EX';
  EX_APPEXCEPTION  = 'APPEXCEPTION';

  //Analytics dimension
  DIM_EVENT        = 'EV';
  EV_FCREATE       = 'FRMCREATE';
  EV_FCLOSE        = 'FRMCLOSE';
  EV_FACTIV        = 'FRMACTIVATE';
  EV_ASAVESTATE    = 'APPSAVESTATE';

  //Analytics dimension
  DIM_ACTION       = 'AC';
  AC_LOADTAB1      = 'LOADTAB1';
  AC_LOADTAB2      = 'LOADTAB2';
  AC_REFRESHTAB    = 'REFRESHTAB';
  AC_REFRESHTAB1   = 'REFRESHTAB1';
  AC_REFRESHTAB2   = 'REFRESHTAB2';
  AC_RETRYTAB      = 'RETRYTAB';
  AC_RETRYTAB1     = 'RETRYTAB1';
  AC_RETRYTAB2     = 'RETRYTAB2';
  AC_ZOOMIN        = 'ZOOMIN';
  AC_ZOOMOUT       = 'ZOOOUT';
  AC_SLIDE         = 'SLIDE';
  AC_SHAREAPP      = 'SHAREAPP';
  AC_SHAREOFFER    = 'SHAREOFF';
  AC_RATE          = 'RATE';
type TdmAnalytics = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FCollectDataPermission: boolean; {$IFDEF ANDROID} FGA: JGoogleAnalytics; FTracker: JTracker; {$ENDIF} public procedure Add(const Name, Value: string; Extra: string = ''); property CollectDataPermission: boolean read FCollectDataPermission write FCollectDataPermission;
  end;

var
  AppAnalytics: TdmAnalytics;

implementation
uses aConsts, aIni;
{%CLASSGROUP 'FMX.Controls.TControl'}

{$R *.dfm}

procedure TdmAnalytics.DataModuleCreate(Sender: TObject);
begin
  //*1: Get user option from ini
  CollectDataPermission:= (Ini.CollectDataPermission = PERMISSION_YES);
  {$IFDEF ANDROID}
  FGA:= TJGoogleAnalytics.JavaClass.getInstance(TAndroidHelper.Context);
  //*2: analytics tracking code
  FTracker:= FGA.getTracker(StringToJString('UA-<your tracking code here>')); 
  FTracker.&set(StringToJString('dimension1'), StringToJString(DIM_EXCEPT));
  FTracker.&set(StringToJString('dimension2'), StringToJString(DIM_EVENT));
  FTracker.&set(StringToJString('dimension3'), StringToJString(DIM_ACTION));
  {$ENDIF}
end;

procedure TdmAnalytics.DataModuleDestroy(Sender: TObject);
begin
  {$IFDEF ANDROID}
  FGA.closeTracker(FTracker);
  {$ENDIF}
end;

procedure TdmAnalytics.Add(const Name, Value: string; Extra: string = '');
begin
  {$IFDEF ANDROID}
  if CollectDataPermission then
    FTracker.sendEvent(StringToJString(Name), StringToJString(Value), StringToJString(Extra), nil);
  {$ELSE}
  {$ENDIF}
end;

end.
==========================
*1 Google says that you can't collect data without user permission, so, 
   CollectDataPermission is based on an answer from the user.
   I have this option as a menu item with a check mark that stores the user 
   selection to a ini file in it's OnClick event. 
*2 In the getTracker method you need to pass your tracking code that Google 
   generates for you. For more information, please go to the analytics website.
In Google Analytics you can see the result like this:

And that's it! This is the Delphi way!

Comentários

  1. Você conseguiu ligar as opções de dados Demográficos, como Idade e sexo dos usuários?

    ResponderExcluir
    Respostas
    1. Sim, os dados demográficos são fornecidos automaticamente pelo Google.

      Excluir
    2. Parabéns pelo artigo. Funcionou perfeito. Só os dafos demograficos no meu, diz que preciso alterar meu codigo, porém o método que o google sugere não existe. Mas obrigado

      Excluir
    3. Parabéns pelo artigo. Funcionou perfeito. Só os dafos demograficos no meu, diz que preciso alterar meu codigo, porém o método que o google sugere não existe. Mas obrigado

      Excluir
  2. Este comentário foi removido pelo autor.

    ResponderExcluir
  3. great job, thanks very much, i need it.

    ResponderExcluir
  4. Do you have something like this for Amazon Analytics?

    ResponderExcluir
    Respostas
    1. Hello!
      Unfortunately not. I didn't do anything for Amazon Analytics. :-\

      Excluir


  5. Thank you for your feedback. We're glad you enjoyed the post. Feel free to share it with others you think may benefit from this information.

    Nintriva-Enterprise Web

    ResponderExcluir

Postar um comentário