Test Script

Saturday, April 27, 2013

Fetching User's Email ID

Hi guys in this tutorial I am going to be showing you how to fetch the user's email Id which has been tied to the users device. This is a very short & simple tutorial so without wasting further time lets get to work :

================================================================
MainActivity.java
================================================================


package com.example.testemail;



import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String emailId = getEmailId();
        Toast.makeText(getApplicationContext(), emailId, 500).show();

}

   public String getEmailId(){

      Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
    
   
    for(Account account: accounts)
    {
        String emailId=account.toString();
        Log.d("List of  email id's of user", emailId);

    }

     String myEmailid=accounts[0].name;

    return myEmailid;
   }

}

================================================================

You also need a permission to access the Accounts 

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

So add the above permission to your Manifest file.

================================================================




So, let me quickly explain what i did above :
1) I created a method which fetches the User's email ID
2) Here we get a Array of Accounts using the AccountManager, notice "getAccountsByType("com.google");" 
that is used to to get all Gmail Accounts configured in the users device

3) "accounts[0].name"  gives me the Email Id of the first Account of the user, which is most likely to be the users actual Gmail Id.

4) Finally added a permission of GET_ACCOUNTS required to access the accounts.

Thats all there is, this is used to fetch user's gmail Id programmatically.


================================================================

Note : Try this on a actual device rather than a emulator because the emulator has no Email Id by default .

If this post helped you, please do drop a comment & i will be happy !

As always feel  free to comment or fire any queries to me ! 



Monday, April 15, 2013

Google Analytics Integration



Hi, so as  promised I am  starting to write a few tutorials !

In this tutorial I am going to teach you how to integrate the latest version of Google Analytics (v2) into your Android app.

Before i begin, let me tell you why your app should have Google Analytics in it.

Google analytics is a great tool for generating reports on your app's performance after users have started using it. Some features of Google Analytics are :


  • Number of active users using their app
  • Demographics of users
  • Adoption and usage of specific features
  • In-app purchases and transactions
  • Number and type of application crashes




So let 's get started on integrating these features in your application .

I will be using two classes to show you how to get this working
a) Main.java
b) Second.java
================================================================

Pre Requisites needed  before we integrate Google Analytics :

1. Create a new Google Analytics Account -->  Create Account

2. Add a new mobile app in your account(This is the app which you want to track)

3. After you add a app in your account,google provides you a tracking Id unique for that app. Note down the tracking ID , it is usually in  UA-XXXX-Y format

4. Download the Google Analytics jar file --->Jar Download Link


==================================================================

Update Manifest File :


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

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



===================================================================

Create a new analytics.xml File :

Create a new xml file in the res/values directory.

XML File

Replace UA-XXXX-Y with the tracking Id you received.

Here we set ga_autoActivityTracking & ga_reportUncaughtExceptions true so that you can monitor your Activities & Exceptions.

Also i have added the following lines so as to give my screens/activities a desired name when it shows up in reports .

 name="com.example.testapp.Main">Main
 name="com.example.testapp.Second">Second


Here name is the complete name of the activity including the package. You have to add all the screens you want to monitor & name them as per desire.


==============================================================
Main.java
==============================================================



package com.example.testapp;

import com.google.analytics.tracking.android.EasyTracker;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button b1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,Second.class);
startActivity(i);
}
});
    }


    @Override
    public void onStart() {
      super.onStart();
       // The rest of your onStart() code.
      EasyTracker.getInstance().activityStart(this); // Add this method.
    }
    
    @Override
    public void onStop() {
      super.onStop();
      // The rest of your onStop() code.
      EasyTracker.getInstance().activityStop(this); // Add this method.
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

=================================================================

So in the above class , i did the following things :

1) Imported Google Analytics package 
2) Added the method  EasyTracker.getInstance().activityStart(this) to start tracking this activity/screen.
3) Added the method  EasyTracker.getInstance().activityStop(this) to stop tracking this activity/screen.
4) Also there is a button which on click opens up Second.java


==============================================================
Second.java
==============================================================

package com.example.testapp;

import com.google.analytics.tracking.android.EasyTracker;

import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sec);
}
  @Override
    public void onStart() {
      super.onStart();
      // The rest of your onStart() code.
      EasyTracker.getInstance().activityStart(this); // Add this method.
    }
   
    @Override
    public void onStop() {
      super.onStop();
      // The rest of your onStop() code.
      EasyTracker.getInstance().activityStop(this); // Add this method.
    }
}

=================================================================

In this class as you can see,i did the exact same things as in Main.java. So you will need to override the onStart & onStop methods of all activities you want to monitor .

That's it ! Pretty simple right? Now once you have done this you can go the dashboard of your Google Analytics account & track the reports.

Note : Google Analytics also provides a feature to measure and track events,i will try to make a new post about it soon. I will be showing how you can track button clicks and other events.

If you need any help or have any request feel free to drop me a comment below !

Monday, April 8, 2013

More Tutorials

So finally i have some time off, so i plan to start a few tutorials on Android ! Currently there is  nothing in particular in my  mind,so if anyone has any requests/suggestions plz let me know & i will try to make a tutorial on the same !

I will eventually be doing a lot of tutorials right from scratch with very clear explanation so that everyone can understand it. I plan to break up my tutorials into small modules. Each module will perform a particular task. So by the end you can have code for almost all functionality within Android.

I find that there is no one place on internet where there are a lot of tutorials right from simplest things so i plan to do that and create a place where a person can find everything on one site itself.

Let me know your views or comments on the same

Also dont forget to see my previous work here :

www.myandroidportfolio.blogspot.com

Saturday, October 6, 2012

Proximity Alerts

Ok here is a simple Tutorial on how to implement the Proximity Alerts in Android.This tutorial is a just a guide on how to use the Proximity Alerts feature in Android & in no way is a complete application by itself.

Here i am going to be using two classes to implement this:
1. MainActivity.java
2. ProximityReciever.java

The MainActvity is the class used to set the Proximity alerts. Here is my Implementation for MainActivity.java:
========================================================================


    public void import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {
LocationManager lm;
double lat=123,long1=34;    //Defining Latitude & Longitude
float radius=3000;                         //Defining Radius
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lm=(LocationManager) getSystemService(LOCATION_SERVICE);
        Intent i= new Intent("com.adnan.proximityalert");           //Custom Action
        PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
        lm.addProximityAlert(lat, long1, radius, -1, pi);
    }


}
========================================================================

Nothing special or any Rocket Science above , here is a small explantion of what i did:

1.Defined the latitude & longitude co-ordinates of the location for which we want to setup the alert.

2.Radius is range for which the alert should work.(This is in meters, so in my example 3km radius)

3.Create a new Intent with a custom action(in my example its "com.adnan.proximityalert")

4.Finally called the addProximityAlert method which takes in the latitude,longitude,radius,expiration time,Pending Intent)

Expiration time is in milliseconds & by setting it to -1 like i did tells the system that the alert never expires.


Now we need a Reciever to listen to the broadcast & do the further things

ProximityReciever.java

========================================================================
android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.widget.Toast;

/*This is the Reciever for the Brodcast sent, here our app will be notified if the User is 
* in the region specified by our proximity alert.You will have to register the reciever 
* with the same Intent you broadcasted in the previous Java file
 * @Author: Adnan A M 
 */


public class ProximityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
// The reciever gets the Context & the Intent that fired the broadcast as arg0 & agr1 
String k=LocationManager.KEY_PROXIMITY_ENTERING;
// Key for determining whether user is leaving or entering 
boolean state=arg1.getBooleanExtra(k, false);
//Gives whether the user is entering or leaving in boolean form
if(state){
// Call the Notification Service or anything else that you would like to do here
Toast.makeText(arg0, "Welcome to my Area", 600).show();
}else{
//Other custom Notification 
Toast.makeText(arg0, "Thank you for visiting my Area,come back again !!", 600).show();

}
}
}

========================================================================


What i did above:

1.Created a Reciever which listens for the broadcast
2.Proximity Alerts use both GPS & Network Provider.
3.Alerts are fired when the user is entering the defined area or leaving the area, so it becomes necessary to determine whether the user is entering the zone or leaving , it is done using KEY_PROXIMITY_ENTERING, this gives a key which is used to retrieve the info whether the user is entering or leaving
4. As shown i used a boolean variable state to store whether the user is entering or Leaving & if no value is recieved i set the default to false
5.Based on the value of state i have two different Toasts.


You need to add the following permissions in manifest as well :


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


Thats it ! You are all set to recieve a alert when you go in a 3kn range of the desired co ordinates !

I will consider writing a second version of this Tutorial extending the concept further & showing its exact in depth usage if needed.


Ok so people have been commenting & sending me queries on how to remove the Proximity alert , so here is how :


========================================================================


private void removeProximityAlert() {

String context = Context.LOCATION_SERVICE;
LocationManager locationManager = (LocationManager) getSystemService(context);

Intent anIntent = new Intent("com.adnan.proximityalert"); 
PendingIntent operation = 
PendingIntent.getBroadcast(getApplicationContext(), unique_id , anIntent, 0);
locationManager.removeProximityAlert(operation);
}


========================================================================

Hope this clears up things better !

Second thing which is most confusing is , what is this "com.adnan.proximityalert"?

Well , that is just something you need to declare , so that line in your code should look like this

"com.yourpackagename.proximityalert".


Please do comment your views about the tutorial & if you have any queries please feel free to drop a comment below !











UA-42774700-1