Integrate Google Analytics SDK to your Android app [Android tutorial]

19 10 2013

Introduction

Google Analytics now can integrate into your Google Play Developer console and show you statistics how your application is used by your users. It gives you:

  • better insight on how it is perceived by your customers, by showing most recent opened screens and user journeys
  • an overview of how often your app is used
  • overview how many times your app is being watched in Google Play store
  • reports on unhandled exceptions
  • reports on inapp purchases
  • times spent on actions
  • and more to read here

This is simple tutorial (based on these instructions) on how to integrate it in your app in a basic scope. If you want more – read what can be monitored here.

1. Download Analytics Services SDK

You can get the library from here. Unfortunately it is not yet available in any maven repository, so you have to download jar file and put it in libs directory.

2. Set up new Google Analytics app property and view (profile)

This will give you tracking ID that you will use further in application code. Now the coding part is left.

3. Add permissions to AndroidManifest.xml file

If your app is not using these, adde them:

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

4. Add tracker methods

These EasyTracher class methods are basic ones that will track your activity start and stop events. Add this code to your Activity’s onStart() method:

EasyTracker.getInstance(this).activityStart(this);

and this method to onStop():

EasyTracker.getInstance(this).activityStop(this);

5. Create your analytics.xml file

This file manages Tracker settings. Put this file in res/values folder. Here is the simpliest file content that will provide tracking ID from step 2, enable Activity tracking and reporting uncaught exceptions. Two simple items to track, however very useful!

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes">

    <string name="ga_trackingId">UA-44734016-1</string>

    <bool name="ga_autoActivityTracking">true</bool>
    <bool name="ga_reportUncaughtExceptions">true</bool>

</resources>

Note that this file contains also warning suppressions. Warning are generated by lint, and are about using dashes (‘-‘) in xml file.

That’s all!

Now your app is ready to send data to Google Analytics. I’ll publish an update with analytics included and let you know how it works! Stay tuned and use PayTogether app!

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android SearchView tutorial: EditText with phone contacts search and autosuggestion (including source code)

15 06 2013

SearchView is available in Android 3.0+. It enables you to search for any data by means of ContentProvider. You can write your custom ContentProvider or use the existing one. For simplicity I will show how to use Android ContactsProvider.

The Goal

The goal is to buil SearchView to find contact from address book with auto suggestions:

SearchView tutorial result

SearchView tutorial result

Download my source code if you wish!

Here it is!

1. Add SearchView to activity

SearchView is aViewGroup and you can add it as any other view to your activity:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SearchViewActivity" >

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" >
    </SearchView>

    <TextView
        android:id="@+id/searchViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/searchView"
        android:layout_centerHorizontal="true"
        android:text="@string/hello_world" />

</RelativeLayout>

2. Create searchable.xml file

In this file you will specify the data source to search through as well as customize the SearchView. In my case I use default Android ContactsProvider. It is identified by URI:

com.android.contacts

Put this file in /res/xml/searchable.xml. This is how my searchable.xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/findContact"
    android:hint="@string/findContact"
    android:includeInGlobalSearch="true"
    android:queryAfterZeroResults="true"
    android:searchMode="queryRewriteFromText"
    android:searchSettingsDescription="@string/findContact"
    android:searchSuggestAuthority="com.android.contacts"
    android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
    android:searchSuggestIntentData="content://com.android.contacts/contacts/lookup" >

    <!-- allow green action key for search-bar and per-suggestion clicks -->
    <actionkey
        android:keycode="KEYCODE_CALL"
        android:queryActionMsg="call"
        android:suggestActionMsg="call" />

</searchable>

Watch out: you have to specify label and hint as a strings from strings.xml. Otherwise (if they are hardcoded or absent, the SearchView did not worked for me).

3. Add permission to read contacts

Add permission in AndroidManifest.xml file in order to gain access to user’s contact book:

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

4. Use searchable.xml in your activity

To use searchable.xml in your activity, you need to add <meta-data/> tag to your AndroidManifest.xml:

<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

To see my full AndroidManifest.xml, see the next points.

5. Setup the SearchView in Activity code

Here you have to provide the SearchManager to the SearchView and point tho this activity as Search Result Intent Handler. Create dedicated method for it and run it in onCreate():

private void setupSearchView() {
	SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	final SearchView searchView = (SearchView) findViewById(R.id.searchView);
	SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
	searchView.setSearchableInfo(searchableInfo);
}

6. Filter SEARCH intent in your activity

SearchView generates the SEARCH intent and handling it in your activity is crucial. This will inform you about refreshing suggestion list, the event of chosing an item from that list or confirmation button press. So add this to intent filter in your activity:

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

As for now your application should work and suggest contacts from contact book. However, choosing the contact from suggestion will not work yet.

7. Add singleTop flag to activity

Now when you choose the contact from suggestion list, the activity is relaunched. To prevent it, set the launchMode to singleTop for your activity in AndroidManifest.xml:

android:launchMode="singleTop"

This is how the full AndroidManifest.xml should look like after all:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pl.looksok.searchviewdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="11" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="pl.looksok.searchviewdemo.SearchViewActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>
</manifest>

8. Handle suggestion pick user action

To handle contact search event you have to handle intent with particular action: search suggestion picked, or return button clicked (search request):

@Override
protected void onNewIntent(Intent intent) {
	if (ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED.equals(intent.getAction())) {
		//handles suggestion clicked query
		String displayName = getDisplayNameForContact(intent);
		resultText.setText(displayName);
	} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
		// handles a search query
		String query = intent.getStringExtra(SearchManager.QUERY);
		resultText.setText("should search for query: '" + query + "'...");
	}
}

this is how I get contact display name:

private String getDisplayNameForContact(Intent intent) {
	Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
	phoneCursor.moveToFirst();
	int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
	String name = phoneCursor.getString(idDisplayName);
	phoneCursor.close();
	return name;
}

That’s all!

Download my source code if you wish!

Here it is!

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android tutorial: Send SMS programatically

4 05 2013

SmsManager has a method that is sending SMS message completely without user’s interaction needed. If You need to send SMS from your code:

1. Use SmsManager

Add these lines to your app

import android.telephony.SmsManager;

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("123456789", null, "sms message", null, null);

You can replace these nulls with Intents (according to documentation) that will be fired up when SMS is delivered / sent / failed to send. In basic case it is optional and can be null.

2. request permissions in AndroidManifest.xml

Add these lines to Manifest:

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

Remember

Remember to have active SIM card in your device when you want to send SMS :)

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Source code: Android custom ListView

27 04 2013

Since many of you have asked for a source code of this tutorial:

Android custom ListView tutorial

I decided to write it and share. The tutorial was witten based on a bigger project, so I could not share it. This is why I have written custom ListView source code example from scratch based on the article mentioned above. Here it is:

Source Code: Android custom ListView zip and on GitHub

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android BroadcastReceiver tutorial: detect outgoing phone call event

13 04 2013

Tutorial shows how to catch outgoing phone call event in Android application (including called phone number information).

This basically consists of catching an Intent that is sent by Android OS while call was initiated. So the BroadcastReceiver is required. Steps to build it are as follows:

1. Create OutgoingCallBroadcastReceiver

This is a BroadcastReceiver that will catch and handle incoming intents. Full implementation is short:

public class OutgoingCallReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(OutgoingCallReceiver.class.getSimpleName(), intent.toString());
		Toast.makeText(context, "Outgoing call catched!", Toast.LENGTH_LONG).show();
		//TODO: Handle outgoing call event here
	}
}

2. Register OutgoingCallBroadcastReceiver in AndroidManifest.xml

Newly created BroadcastReceiver will wait for android.intent.action.NEW_OUTGOING_CALL intent actions. In order to direct such intents to Receiver add this code to AndroidManifest.xml:

<receiver android:name=".OutgoingCallReceiver" >
	<intent-filter>
		<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
	</intent-filter>
</receiver>

3. Add permission in AndroidManifest.xml

Your application will now need to request for PROCESS_OUTGOING_CALLS permission. Add that request to AndroidManifest.xml:

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

4. Get called phone number (optional)

Intent that I just catched has Extra with phone number, so if you need it, just get that String Extra from intent with:

String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

Just add the foregoing line to the OnReceive method:

@Override
public void onReceive(Context context, Intent intent) {
	String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
	Log.d(OutgoingCallReceiver.class.getSimpleName(), intent.toString() + ", call to: " + phoneNumber);
	Toast.makeText(context, "Outgoing call catched: " + phoneNumber, Toast.LENGTH_LONG).show();
	//TODO: Handle outgoing call event here
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android: change desktop wallpaper programatically

16 03 2013

Here is an instruction how to change desktop background on android device rogramatically by means of WallpaperManager. For simplicity the new wallpaper is taken from project resources.

private void setDesktopWallpaper() {
	try {
		WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
		wallpaperManager.setResource(R.drawable.my_wallpaper);
	} catch (IOException e) {
		SLog.e(TAG, "Error changing wallpaper: " + e.getMessage());
	}
}

To use another image (for example downloaded from the internet, you can use setBitmap method instead of setResource.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android: play default notification sound

9 03 2013

When aplication wants to notify user with sound, the best way to do it is to play notification sound that is set by the user on his device.

To do it, first you need to get Uri to that audio file from RingtoneManager. After that create a Ringtone object from that Uri and play it:

private void playDefaultNotificationSound() {
	Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
	Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
	r.play();
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!








%d bloggers like this: