Friday 27 February 2015

HB Blog 60: Google Analytics Android Integration.

Gooe Analytics is a service offered by Google that generates detailed statistics about a website's and mobile traffic and their traffic sources and measures conversions and sales.The Google Analytics SDK for Android makes it easy for developers to collect user engagement data from their apps. Additionally, the Google Analytics SDK for Android gives you the tools to monitor the success of mobile marketing campaign by providing end-to-end visibility into the performance of your marketing channels, from Google Play installs through in-app purchases and transactions.

Developers can then use Google Analytics reports to measure:
    The number of active users are using their applications.
    From where in the world the application is being used.
    Adoption and usage of specific features.
    In-app purchases and transactions.
    The number and type of application crashes.
    And many other useful metrics.

There are following steps to getting started with the SDK,
1)First login to Google Analytics site and get tracking id for your project.
2)Then, add Google Analytics library(libGoogleAnalyticsServices.jar) to your project and clear the dependencies that are required.
3)Then add following files and code snippnet to make it run.
    Update AndroidManifest.xml - For network permissions.
    Add EasyTracker methods - For initiating Google Analytics.
    Create your analytics.xml file - For mainting unique tracking details via tracking code.

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Have a look on few code snippets,

Here I have create array bound exception as well as Demo Event which will be tracked by Google Analytics,
//MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a[] = new int[2];
                System.out.println("Access element three :" + a[3]);
            }
        });

        // May return null if a EasyTracker has not yet been initialized with a
        // property ID.
        EasyTracker easyTracker = EasyTracker.getInstance(this);
        // MapBuilder.createEvent().build() returns a Map of event fields and values
        // that are set and sent with the hit.
        easyTracker.send(MapBuilder
                        .createEvent("Demo Event category",     // Event category (required)
                                "Demo Event action",  // Event action (required)
                                "Demo Event label",   // Event label
                                (long)1234)            // Event value
                        .build()
        );
    }

    @Override
    public void onStart() {
        super.onStart();
        // Google Analytics Tracker onStart() code.
        EasyTracker.getInstance(this).activityStart(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        // Google Analytics Tracker onStop() code.
        EasyTracker.getInstance(this).activityStop(this);
    }
}

//analytics.xml
1
2
3
4
5
6
7
8
<resources><!-- xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes" -->
<!-- Replace placeholder ID with your tracking ID -->
<string name="ga_trackingId">UA-xxxxxxxxx-X</string>
<!-- Enable automatic activity tracking -->
<bool name="ga_autoActivityTracking">true</bool>
<!-- Enable automatic exception tracking -->
<bool name="ga_reportUncaughtExceptions">true</bool>
</resources>

Saturday 21 February 2015

HB Blog 59: Asynchronous Operations In Android And iOS.

Asynchronous Operations In Android:-
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute. AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

The three types used by an asynchronous task are the following:
1)Params, the type of the parameters sent to the task upon execution.
2)Progress, the type of the progress units published during the background computation.
3)Result, the type of the result of the background computation.

When an asynchronous task is executed, the task goes through 4 steps:
    onPreExecute() - It invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface. We can stop further background process in case of webservice parsing while no internet connection is found.
    doInBackground(Params...) - It is invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
    onProgressUpdate(Progress...) - It is invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing.
    onPostExecute(Result) - It is invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Here is skeleton for AsyncTask,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Async_DemoTask extends AsyncTask<String, String, String> {
  
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    // Doing something on the main thread before the task is executed
       //start progress bar
       //check internet connection
    }

    @Override
    public String doInBackground(String... params) {
       // Perform long running process
        return response;
    }

    @Override
    protected void onPostExecute(String success) {
        super.onPostExecute(success);
       //stop progress bar
       //Update the UI
    }
}

Asynchronous Operations In iOS:-
Grand Central Dispatch (GCD) comprises language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in iOS and OS X. With GCD, you can line up blocks of code in a queue for the system to execute as necessary. These blocks or operations, will be dispatched in the queue to another thread, leaving your main UI thread to continue its tasks.

dispatch_queue_create - It creates a new dispatch queue to which blocks can be submitted.
dispatch_get_main_queue - It returns the serial dispatch queue associated with the application’s main thread.This queue is created automatically on behalf of the main thread before main is called. This method is useful for updating UI.

Here is skeleton for dispatch_async,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Doing something on the main thread
dispatch_queue_t demoQueue = dispatch_queue_create("demo queue",NULL);
dispatch_async(demoQueue, ^{
    // Perform long running process
    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI       
    });
});
// Continue doing other stuff on the
// main thread while process is running.

Saturday 14 February 2015

HB Blog 58: Logo Programming Basic.

Logo is an educational programming language, designed in 1967 by Daniel G. Bobrow, Wally Feurzeig, Seymour Papert and Cynthia Solomon. Logo is a multi-paradigm adaptation and dialect of Lisp, a functional programming language. It is the most interesting programming language for children to learn. It was my first programming language and personally speaking I liked the turtle. Basically, the environment goes like a terminal with screen and terminal at bottom. The screen has turtle(robot logo) which is like our starting point or say mouse pointer. As we provide commands in terminal appropriate actions are performed by this turtle.

Following are few basic commands,
fd - It moves turtle forward command with specific units
bk - It moves turtle backward command with specific units
rt - It moves turtle right command with specific units
lt - It moves turtle left command with specific units
cs - It clears the screen.
repeat - It repeats the commands.
pu - It pen up the turtle which makes turtle to stop writing
pd - It pen down the turtle which makes turtle to start writing
ht - It makes turtle hide
st - It makes turtle visible
home - It causes the turtle to return to the center of the screen
label - It takes a single word as a quoted string and print them on the graphics window at the location of the turtle
setxy - It takes two arguments, treats the first as the value of the abscissa (horizontal axis) and the second as a value of the ordinate (vertical axis)
make - It takes a single word as a local variable to contain value.
print - It prints given values.
random - It prints random values.
to - It starts the command loop.
end - It ends the command loop.

Have a look on a code snippets, which will draw a simple box,
1
2
3
4
5
forward 100
right 90
forward 100
right 90
fd 100 rt 90 fd 100 rt 90

Sunday 8 February 2015

HB Blog 57: Trojan Horse Invades.

Viruses, worms, Trojans, and bots are all part of a class of software called malware. Malware or malicious code (malcode) is short for malicious software. It is code or software that is specifically designed to damage, disrupt, steal, or in general inflict some other “bad” or illegitimate action on data, hosts, or networks.
Trojan horse malware is one of the most famous and deadly virus. It is named after the ancient story in which Greeks used horse ship build of wood to invade city of troy. Similarly this kind application is seen in this malware. A Trojan horse, or Trojan, in computing is a generally non-self-replicating type of malware program containing malicious code that, when executed, carries out actions determined by the nature of the Trojan, typically causing loss or theft of data, and possible system harm. A Trojan often acts as a backdoor, contacting a controller which can then have unauthorized access to the affected computer. A Trojan may give a hacker remote access to a targeted computer system. Operations that could be performed by a hacker, or be caused unintentionally by program operation, on a targeted computer system.The main difference amid a normal computer virus and a Trojan horse is that it is not specifically developed for spreading themselves. In its place Trojan horse virus is downloaded either as an infected file from internet, or as payload of some other virus. This virus is capable of stealing end-user information and downloading other malware to a computer too. To fight with this treacherous virus, your computer is equipped with firewall and you can also install antivirus software in your system. However, an antivirus is not always effective against Trojan horse, so at that instance the way out of the problem is to remove Trojan horse virus manually.After recognizing a file infected with Trojan horse, it becomes easy to remove it. Usually, your system will give you DLL error, which is associated with Trojan attack.

Few notable Trojan horses malware are as follows:
    Netbus Advance System Care(by Carl-Fredrik Neikter)
    Subseven or Sub7(by Mobman)
    Back Orifice (Sir Dystic)
    Beast
    Zeus
    Flashback Trojan (Trojan BackDoor.Flashback)
    ZeroAccess
    Koobface
    Vundo

Tuesday 3 February 2015

HB Blog 56: Android Lifecycles (Activity/Fragment/Service).

Unlike other programming paradigms in which apps are launched with a main() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its life cycle. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.
The activity life cycle consists methods such as onCreate(), onStart(), onResume(), onRestart(), onPause(), onStop() and onDestroy().

onCreate() - Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.
onStart() - Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().
onResume() - Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.
onRestart() - Called after onStop() when the current activity is being re-displayed to the user (the user has navigated back to it). It will be followed by onStart() and then onResume().
onPause() - Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
onStop() - Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
onDestroy() - Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
The fragment life cycle consists methods such as onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart(), onResume(), onPause(), onStop(),
onDestroyView(), onDestroy(), onDetach().

onAttach() - It is called once the fragment is associated with its activity.
onCreate() - It is called to do initial creation of the fragment.
onCreateView() - It creates and returns the view hierarchy associated with the fragment.
onActivityCreated() - It tells the fragment that its activity has completed its own Activity.onCreate()
onStart() - It makes the fragment visible to the user (based on its containing activity being started).
onResume() - It makes the fragment interacting with the user (based on its containing activity being resumed).
onPause() -  It is called when fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
onStop() - It is called when  fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
onDestroyView() - It allows the fragment to clean up resources associated with its View.
onDestroy() - It is   called to do final cleanup of the fragment's state.
onDetach() - It is   called immediately prior to the fragment no longer being associated with its activity.

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.The services life cycle consists methods such as,

Unbounded Services: onCreate(), onStartCommand(), onDestroy().
onCreate() - The system calls this method when the service is first created, to perform one-time setup procedures.
onStartCommand() - The system calls this method when another component, such as an activity, requests that the service be started, by calling startService().
onDestroy() - The system calls this method when the service is no longer used and is being destroyed.

Bounded Services: onCreate(), onBind(), onUnbind(), onDestroy().
onCreate() - It is called by the system when the service is first created. Do not call this method directly.
onBind() - The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService().
onUnbind() - It is called when all clients have disconnected from a particular interface published by the service.
onDestroy() - The system calls this method when the service is no longer used and is being destroyed.