Pull to refresh

Подключаем Yandex.Metrica в Xamarin.Android

Привет, Хабр!

Недавно мне понадобилось подключить систему для сбора данных о действиях пользователей и мой выбор пал на Yandex.Metrica для приложений. И я с удивлением обнаружил, что нет не одной инструкции, как подключить метрику в приложение, которое написано на Xamarin.

Всем, кому интересно как это сделать — прошу пожаловать под кат.

1. Создаём приложение




2. Загружаем библиотеку для работы с метрикой


Загружаем отсюда yandex-mobmetrica-lib-android-1.60-wlibs.jar.

3. Создаём binding library




4. Добавляем в проект скачанную библиотеку


Добавляем в папку Jars скачанную библиотеку:



Выставляем Build Action: EmbeddedJar.



5. Добавляем в основной проект ссылку на только что созданный проект





6. Создаём в папке Providers файл MetricaContentProvider.cs с таким содержанием:


namespace HabrYandexMetrica.Providers
{
    public class MetricaContentProvider : Com.Yandex.Metrica.MetricaContentProvider
    {
    }
}

7. Добавляем в AndroidManifest.xml такие строчки:


  <!-- Yandex Metrica required permission. Open network sockets -->
  <uses-permission android:name="android.permission.INTERNET"/>
  <!-- Yandex Metrica required permission. Access information about networks -->
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <!-- Yandex Metrica optional permission. Approximate location derived from network location sources such as cell towers and Wi-Fi -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <!-- Yandex Metrica optional permission. Precise location from location sources such as GPS, cell towers, and Wi-Fi -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <!-- Yandex Metrica optional permission. Wifi state: mac, ssid, ... -->
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  
	<application>
		<!-- start of Yandex Metrica -->
		<service android:name="com.yandex.metrica.MetricaService" android:enabled="true" android:exported="true" android:process=":Metrica">
			<intent-filter>
				<category android:name="android.intent.category.DEFAULT" />
				<action android:name="com.yandex.metrica.IMetricaService" />
				<data android:scheme="metrica" />
			</intent-filter>
			<meta-data android:name="metrica:api:level" android:value="16" />
		</service>
		<receiver android:name="com.yandex.metrica.MetricaEventHandler" android:enabled="true" android:exported="true">
			<intent-filter>
				<action android:name="com.yandex.metrica.intent.action.SYNC" />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.PACKAGE_ADDED" />
				<action android:name="android.intent.action.PACKAGE_DATA_CLEARED" />
				<data android:scheme="package" />
			</intent-filter>
			<!-- Необходимо для трэкинга кампаний -->
			<intent-filter>
				<action android:name="com.android.vending.INSTALL_REFERRER" />
			</intent-filter>
		</receiver>
		<provider android:name="habryandexmetrica.providers.MetricaContentProvider" android:authorities="HabrYandexMetrica.HabrYandexMetrica.MetricaContentProvider" android:enabled="true" android:exported="true"/>
    <!-- end of Yandex Metrica -->
	</application>


8. Инициализируем мертику в MainActivity



using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Com.Yandex.Metrica;

namespace HabrYandexMetrica
{
    [Activity(Label = "HabrYandexMetrica", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            YandexMetrica.Initialize(Application.Context,"111");

            SetContentView(Resource.Layout.Main);
        }

        protected override void OnResume()
        {
            YandexMetrica.OnResumeActivity(this);
            base.OnResume();
        }

        protected override void OnPause()
        {
            YandexMetrica.OnPauseActivity(this);
            base.OnPause();
        }
    }
}


Всё, метрика готова к работе.

Тут можно подсмотреть методы, которые доступны.
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.