5

Quero usar o Google Analytics para coletar mais informações sobre o uso de meus aplicativos, como adicionar o Google Analytics ao meu aplicativo Android?

1 Resposta 1

7

Configuração do projeto

Atualize o arquivo AndroidManifest.xml do seu projeto para incluir as permissões INTERNET e ACCESS_NETWORK_STATE:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.analytics">

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

  <application android:name="AnalyticsApplication">
    ...
  </application>
</manifest>

O plug-in do Google Services para Gradle analisa informações de configuração do arquivo google-services.json.

Para adicionar o plug-in ao seu projeto, atualize seus arquivos build.gradle de nível projeto e build.gradle no nível do aplicativo da seguinte forma:

  1. Adicione a dependência ao arquivo build.gradle no nível do projeto:

    classpath 'com.google.gms:google-services:1.5.0-beta2'
    
  2. Adicione o plug-in ao arquivo build.gradle no nível do aplicativo:

    apply plugin: 'com.google.gms.google-services'
    

Agora, você precisa adicionar uma dependência ao Google Play Services. Dentro do arquivo build.gradle do seu aplicativo, adicione:

compile 'com.google.android.gms:play-services-analytics:8.4.0'

Acessar um arquivo de configuração

O arquivo de configuração fornece informações específicas de serviço para seu aplicativo. Para acessá-lo, você precisa selecionar um projeto existente para seu aplicativo ou criar um novo. Você também precisa fornecer um nome de pacote para seu aplicativo.


Observação: você precisa ter uma conta do Google Analytics e uma propriedade registrada para acessar o arquivo de configuração.

Clique no link abaixo para acessar um arquivo de configuração a ser adicionado ao seu projeto.

ACESSAR UM ARQUIVO DE CONFIGURAÇÃO

Adicionar o arquivo de configuração ao seu projeto

Copie o arquivo google-services.json que você acabou de receber no diretório app/ ou mobile/ do seu projeto do Android Studio.

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}
AnalyticsApplication.java

Activity ou Fragment

Abra a atividade que você deseja acompanhar.

Você também pode acompanhar um Fragment, mas ele precisa representar corretamente a exibição de tela.

Inclua no método onCreate da Activity ou do Fragment que deseja acompanhar para acessar a instância do Tracker compartilhado:

// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();

Inclua o código abaixo no método apropriado, como onResume para uma Activity ou onPageSelected para um ViewPager com a finalidade de registrar quando a tela muda.

Log.i(TAG, "Setting screen name: " + name);
mTracker.setScreenName("Image~" + name);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());

Adicione o código de acompanhamento a cada Activity ou Fragment que representa uma tela. Defina um nome dentro de cada Activity ou Fragment se você quiser diferenciar exibições de tela para seu aplicativo no Google Analytics. Todas as atividades gravadas no rastreador compartilhado enviam o nome de tela mais recente até que ele seja substituído ou apagado (definido como null).

Envio de um evento

Para enviar um evento, defina os valores dos campos de tela no rastreador e envie o hit. O exemplo a seguir usa o HitBuilders.EventBuilder para enviar um Event:

mTracker.send(new HitBuilders.EventBuilder()
    .setCategory("Action")
    .setAction("Share")
    .build());

Código Completo:

MainActivity.java:

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import java.util.Locale;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

/**
 * Activity which displays numerous background images that may be viewed. These background images
 * are shown via {@link ImageFragment}.
 */
public class MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";

  private static final ImageInfo[] IMAGE_INFOS = {
      new ImageInfo(R.drawable.favorite, R.string.pattern1_title),
      new ImageInfo(R.drawable.flash, R.string.pattern2_title),
      new ImageInfo(R.drawable.face, R.string.pattern3_title),
      new ImageInfo(R.drawable.whitebalance, R.string.pattern4_title),
  };

  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each image.
   * This uses a {@link FragmentPagerAdapter}, which keeps every loaded fragment in memory.
   */
  @SuppressWarnings("FieldCanBeLocal")
  private ImagePagerAdapter mImagePagerAdapter;

  /**
   * The {@link ViewPager} that will host the patterns.
   */
  private ViewPager mViewPager;

  /**
   * The {@link Tracker} used to record screen views.
   */
  private Tracker mTracker;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // [START shared_tracker]
    // Obtain the shared Tracker instance.
    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();
    // [END shared_tracker]

    // Create the adapter that will return a fragment for each image.
    mImagePagerAdapter = new ImagePagerAdapter(getSupportFragmentManager(), IMAGE_INFOS);

    // Set up the ViewPager with the pattern adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mImagePagerAdapter);

    // When the visible image changes, send a screen view hit.
    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
      @Override
      public void onPageSelected(int position) {
        sendScreenImageName();
      }
    });

    // Send initial screen screen view hit.
    sendScreenImageName();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
      case R.id.menu_share:
        // [START custom_event]
        mTracker.send(new HitBuilders.EventBuilder()
            .setCategory("Action")
            .setAction("Share")
            .build());
        // [END custom_event]

        String name = getCurrentImageTitle();
        String text = "I'd love you to hear about " + name;

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, text);
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
        break;
    }
    return false;
  }

  /**
   * Return the title of the currently displayed image.
   * @return title of image
   */
  private String getCurrentImageTitle() {
    int position = mViewPager.getCurrentItem();
    ImageInfo info = IMAGE_INFOS[position];
    return getString(info.title);
  }

  /**
   * Record a screen view hit for the visible {@link ImageFragment} displayed
   * inside {@link FragmentPagerAdapter}.
   */
  private void sendScreenImageName() {
    String name = getCurrentImageTitle();

    // [START screen_view_hit]
    Log.i(TAG, "Setting screen name: " + name);
    mTracker.setScreenName("Image~" + name);
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    // [END screen_view_hit]
  }

  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
   * one of the sections/tabs/pages.
   */
  public class ImagePagerAdapter extends FragmentPagerAdapter {

    private final ImageInfo[] infos;

    public ImagePagerAdapter(FragmentManager fm, ImageInfo[] infos) {
      super(fm);
      this.infos = infos;
    }

    @Override
    public Fragment getItem(int position) {
      ImageInfo info = infos[position];
      return ImageFragment.newInstance(info.image);
    }

    @Override
    public int getCount() {
      return infos.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      if (position < 0 || position >= infos.length) {
        return null;
      }
      Locale l = Locale.getDefault();
      ImageInfo info = infos[position];
      return getString(info.title).toUpperCase(l);
    }
  }
}

AnalyticsApplication.java

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}
0

Você deve fazer log-in para responder a esta pergunta.