Friday, April 29, 2016

R.java Internal working and its role in android application.

I am writing this blog because usually android professional use R.java file but most of the people doesn’t know how it works and how it get generated etc. I hope this blog will help to understand such things. You can post me if it helps to you.  
R.java Role and works in java:
R.java Files binds resources and code for the same it use some integer it use public static final int type unique ID. If user users uses Eclipse or android studio and once compile their android project this R.java file is automatically generated in gen folder of project.
Process of R.java
1)      We drag a button from palette and place it in the xml.
2)      As soon as we provide an id to the button, an entry inside R.java class gets created               automatically. As shown in image button1 is added in
R.java -> id -> button1 = some hexadecimal number
3)       We write the code:  Button btn = (Button)findViewById(R.id.button1);
Button btn – Creating a new object of class Button
findViewById(R.id.button1)  – A method to find views in xml files
(Button)  – Casting the view into button type. Casting is needed because findViewById() doesn’t specify the view type. In case the view defined in XML is not found a button, casting as a button in java code will trigger an Invalid cast exception at runtime.
Internal working of R.java
These are the internal works of R.java how it generated and how to it bind the XML and code and how it generate unique ID.
At build time, the aapt tool collects all of the resources you have defined (though separate files or explicit definitions in files) and assigns resource IDs to them.
A resource ID is a 32 bit number of the form: PPTTNNNN. PP is the package the resource is for; TT is the type of the resource; NNNN is the name of the resource in that type. For applications resources, PP is always 0x7f.
The TT and NNNN values are assigned by aapt arbitrarily -- basically for each new type the next available number is assigned and used (starting with 1); likewise for each new name in a type, the next available number is assigned and used (starting with 1).
So if we have these resource files handled by aapt in this order:
layout/main.xml
drawable/icon.xml
layout/listitem.xml
The first type we see is "layout" so that is given TT == 1. The first name under that type is "main" so that is given NNNN == 1. The final resource ID is 0x7f010001.
Next we see "drawable" so that is given TT == 2. The first name for that type is "icon" so that gets NNNN == 1. The final resource ID is 0x7f020001.
Last we see another "layout" which has TT == 1 as before. This has a new name "listitem" so that gets the next value NNNN == 2. The final resource ID is 0x7f010002.
Note that aapt by default makes no attempt to keep these identifiers the same between builds. Each time the resources change, they can all get new identifiers. Each time they are built, a new R.java is created with the current identifiers so your code gets the correct values. Because of this, you must never persistent resource identifiers anywhere where they can be used across different builds of your app.
Once the resources are compiled and identifiers assigned, aapt generates the R.java file for your source code and a binary file called "resources.arsc" that contains all of the resource names, identifiers, and values (for resources that come from separate file, their value is the path to that file in the .apk), in a format that can easily mmapped and parsed on the device at runtime.
You can get a summary of the resources.arsc file in an apk with the command "aapt dump resources <path-to-apk>".
The format of the binary resource table is documented in the header file for the resource data structures here:
The full implementation for reading the resource table on the device is here:

Wednesday, April 27, 2016

Android application optimization and increase performance

These are the following things developer should keep care while writing code for android application. It helps to improve code quality as well as performance of application.

·         UI Optimization:
Use less images and try to use less size image in your XML UI. Do not put unwanted images in background try to use colors instead of image .Make sure your layouts are as simple as possible, without unnecessary layout elements. When the view hierarchy gets too deep, the UI engine have trouble traversing all the views and calculating the position of all elements. For example, if you create a custom control and include it in another layout element, it can add an extra view that is not necessary to display the UI and that will slightly slow down the application. You can analyze your view hierarchy to see where your layout can be flattened with the Hierarchy Viewer tool. The tool can be opened from Eclipse using the Dump View Hierarchy for UI Automator icon in the DDMS perspective, or launch the standalone tool hierarchyviewer in the <sdk>\tools\ directory.

·         Memory Leak:
Although Android is a memory managed environment, don’t let this lull you into a false sense of security—memory leaks can still happen. This is because garbage collection (GC) can only remove objects that it recognizes as unreachable. If it doesn’t spot an unreachable object, then that object isn’t going to get garbage collected.
These unreachable objects hang around, polluting your heap, and taking up valuable space. As your app continues to leak objects, the amount of usable space gets smaller and smaller, which in turn triggers more frequent and longer GC events
This problem is that mobile devices tend to be short on memory to begin with, so a memory leak can quickly escalate into an OutOfMemoryError, crashing your app.
To sort out this kind off problem you have to use tool Memory Monitor. This tool is built into Android Studio, so you access it by clicking the Memory tab towards the bottom of your IDE.
If Memory Monitor is returning a No debuggable applications message, open Android Studio’s Tools menu, select Android, and make sure Enable adb integration is selected. This feature can be temperamental, so you may need to toggle Enable adb integration on and off a couple of times. It may also help to remove your Android device and then reconnect it.
Once Memory Monitor has detected your running application, it’ll display the amount of memory your app is using in dark blue and the unallocated memory in light blue

·         Background task Optimization:
1)    Operations that can take a long time should run on their own thread and not in the main (UI) thread. If an operation takes too long while it runs on the main thread, the Android OS may show an Application not responding (ANR) dialog : from there, the user may choose to wait or to close your application. This message is not very user-friendly and your application should never have an occasion to trigger it. In particular, web services calls to an external API are especially sensitive to this and should always be on their own thread, since a network slowdown or a problem on their end can trigger an ANR, blocking the execution of your application. You can also taken advantages of threads to pre-calculate graphics that are displayed later on on the main thread

2)    If your application requires a lot of call to external APIs, avoid sending the calls again and again if the wifi and cellular networks are not available. It is a waste of resources to prepare the whole request, send it off and wait for a timeout when it is sure to fail. You can pool the status of the connexion regularly, switch to an offline mode if no network is available, and reactivate it as soon as the network comes back.

·         Caching:
Advantage of caching to reduce the impact of expensive operations. Calculations that are long but for which the result won’t change or graphics that will be reused can be kept in memory. You can also cache the result of calls to external APIs to a local database so you won’t depend on that resource being available at all times. A call to a local database can be faster, will not use up your users’ data plan and will work even it the device is offline. On the other hand, you should plan for a way to fresh that data from time to time, for example keeping a time and date stamp and refreshing it when it’s getting old.

·         Strict Mode:
 You should avoid performing long running operations on the UI thread. This includes file and network access.
To ensure this you can use StrictMode. StrictMode is available as of API 9 (Android 2.3.3) and allows to setup thread policies for your application.
Via StrictMode you can instruct the Android system to crash your application if it performs long running operations, e.g. I/O in the user interface thread.
Example:

package com.app.strictmode;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

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

public class TestStrictMode extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Activate StrictMode
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()
         // alternatively .detectAll() for all detectable problems
        .penaltyLog()
        .penaltyDeath()
        .build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
         .detectLeakedSqlLiteObjects()
         .detectLeakedClosableObjects()
        // alternatively .detectAll() for all detectable problems
        .penaltyLog()
        .penaltyDeath()
        .build());
   
    // Test code
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String eol = System.getProperty("line.separator");
    try {
      BufferedWriter writer =
          new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile",
              MODE_WORLD_WRITEABLE)));
      writer.write("This is a test1." + eol);
      writer.write("This is a test2." + eol);
      writer.write("This is a test3." + eol);
      writer.write("This is a test4." + eol);
      writer.write("This is a test5." + eol);
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


Tuesday, April 26, 2016

Protobuff communication in Android

Protobuff in android:

I am writing this blog on .proto file communication because as I try to search for the same I did not found much solution on the same. So I have try to make simplify with example so that everyone understand easily. I hope this blog would be helpful for developers

There are few choices in android that can be used for sharing data or transfer data over the network like rest and soap few way of communication json parsing, Xml parsing, Soap parsing (xml) etc.
Here I want to explain one more way to communicate is protobuf API . This provide faster performance rather than XML and JSON.

In android we use this over HTTP Url connection or Http client. Data travels in the binary format.
There is a basic reason for faster performance i.e. XML is notoriously space intensive, and encoding/decoding it can impose a huge performance penalty on applications.

Requirement for protobuff communication is

1.       Define message formats in a .proto file.
2.       Use the protocol buffer compiler.
3.       Use the Java protocol buffer API to write and read messages.
4.       And require google protobuf.jar library
In this method you have to configure a proto file that contains message format which we use for parsing data.
Here I am showing an example addressbook.proto file which you find on google site also.

1)   Define Protocol Format

To create your address book application, you'll need to start with a .proto file. The definitions in a .proto file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message.
package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";
message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

2)   Compilation of .proto

Here is steps for compile .proto file
If you haven't installed the compiler, https://developers.google.com/protocol-buffers/docs/downloads  and follow the instructions in the README.
Now run the compiler, specifying the source directory (where your application's source code lives – the current directory is used if you don't provide a value), the destination directory (where you want the generated code to go; often the same as $SRC_DIR), and the path to your .proto. In this case, you...:
protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
Because you want Java classes, you use the --java_out option – similar options are provided for other supported languages.
If you look in AddressBookProtos.java (Generated File), you can see that it defines a class called AddressBookProtos, nested within which is a class for each message you specified in addressbook.proto. Each class has its ownBuilder class that you use to create instances of that class. You can find out more about builders in theBuilders vs. Messages section below.
Both messages and builders have auto-generated accessor methods for each field of the message; messages have only getters while builders have both getters and setters. Here are some of the accessors for the Personclass (implementations omitted for brevity)
Here is few sample code
/ required string name = 1;
public boolean hasName();
public java.lang.String getName();
public Builder setName(String value);
public Builder clearName();

// required int32 id = 2;
public boolean hasId();
public int getId();
public Builder setId(int value);
public Builder clearId();

// optional string email = 3;
public boolean hasEmail();
public String getEmail();
public Builder setEmail(String value);
public Builder clearEmail();

// repeated .tutorial.Person.PhoneNumber phone = 4;
public List<PhoneNumber> getPhoneList();
public int getPhoneCount();
public PhoneNumber getPhone(int index);
public Builder setPhone(int index, PhoneNumber value);
public Builder addPhone(PhoneNumber value);
public Builder addAllPhone(Iterable<PhoneNumber> value);
public Builder clearPhone();

3)   Writing a message

Here is a program which reads an AddressBook from a file, adds one new Person to it based on user input, and writes the new AddressBook back out to the file again. The parts which directly call or reference code generated by the protocol compiler are highlighted

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

class AddPerson {
  // This function fills in a Person message based on user input.
  static Person PromptForAddress(BufferedReader stdin,
                                 PrintStream stdout) throws IOException {
    Person.Builder person = Person.newBuilder();

    stdout.print("Enter person ID: ");
    person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print("Enter name: ");
    person.setName(stdin.readLine());

    stdout.print("Enter email address (blank for none): ");
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);
    }

    while (true) {
      stdout.print("Enter a phone number (or leave blank to finish): ");
      String number = stdin.readLine();
      if (number.length() == 0) {
        break;
      }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

      stdout.print("Is this a mobile, home, or work phone? ");
      String type = stdin.readLine();
      if (type.equals("mobile")) {
        phoneNumber.setType(Person.PhoneType.MOBILE);
      } else if (type.equals("home")) {
        phoneNumber.setType(Person.PhoneType.HOME);
      } else if (type.equals("work")) {
        phoneNumber.setType(Person.PhoneType.WORK);
      } else {
        stdout.println("Unknown phone type.  Using default.");
      }

      person.addPhone(phoneNumber);
    }

    return person.build();
  }

  // Main function:  Reads the entire address book from a file,
  //   adds one person based on user input, then writes it back out to the same
  //   file.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    AddressBook.Builder addressBook = AddressBook.newBuilder();

    // Read the existing address book.
    try {
      addressBook.mergeFrom(new FileInputStream(args[0]));
    } catch (FileNotFoundException e) {
      System.out.println(args[0] + ": File not found.  Creating a new file.");
    }

    // Add an address.
    addressBook.addPerson(
      PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                       System.out));

    // Write the new address book back to disk.
    FileOutputStream output = new FileOutputStream(args[0]);
    addressBook.build().writeTo(output);
    output.close();
  }
}

4)   Reading a message

In this communication data send and receive as a Raw data in byte array format therefore in serialize and desterilize you have to convert using following methods
byte[] toByteArray();: serializes the message and returns a byte array containing its raw bytes.
static Person parseFrom(byte[] data);: parses a message from the given byte array.
void writeTo(OutputStream output);: serializes the message and writes it to an OutputStream.
static Person parseFrom(InputStream input);: reads and parses a message from an InputStream
Example to read message:
import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;

class ListPeople {
  // Iterates though all people in the AddressBook and prints info about them.
  static void Print(AddressBook addressBook) {
    for (Person person: addressBook.getPersonList()) {
      System.out.println("Person ID: " + person.getId());
      System.out.println("  Name: " + person.getName());
      if (person.hasEmail()) {
        System.out.println("  E-mail address: " + person.getEmail());
      }

      for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
        switch (phoneNumber.getType()) {
          case MOBILE:
            System.out.print("  Mobile phone #: ");
            break;
          case HOME:
            System.out.print("  Home phone #: ");
            break;
          case WORK:
            System.out.print("  Work phone #: ");
            break;
        }
        System.out.println(phoneNumber.getNumber());
      }
    }
  }

  // Main function:  Reads the entire address book from a file and prints all
  //   the information inside.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    // Read the existing address book.
    AddressBook addressBook =
      AddressBook.parseFrom(new FileInputStream(args[0]));

    Print(addressBook);
  }
}

5)   Sample code to send data over the network

Here is an example for sending byte array which we marshaled with protobuff message format

public static Object callServerWithPayload(String methodName, byte[] data, String... params)
{
DefaultHttpClient client = new DefaultHttpClient();
StringBuilder sb = new StringBuilder();
sb.append(SERVER_ADDRESS + SERVLET_PATH);
sb.append(“/”).append(methodName);
for (String param : params)
{
sb.append(“/”).append(URLEncoder.encode(param));
}
HttpPost method = new HttpPost(sb.toString());
method.setEntity(new ByteArrayEntity(data));
try
{
HttpResponse response = client.execute(method);
return response.getEntity().getContent();
}
catch (Exception e)
{
App.logException(e);
}

















Monday, April 25, 2016

Android interview question for experienced professionals

At certain level of Experience inteviewer wants to hire a person that have good technical skill as well as very deep knowledge about life cycle of project, design of application, performance improvement of application and automation etc.

As my personal experience android interview generaly moves on  two way first if interviewer belongs from JAVA background (J2EE) then he will completly ask question related to CORE JAVA and most of the focus on Multithreading,Collections ,Strings ,Exceptional Handling and very few questions on ANDROID  therefore android people have to explore these also even though android have their on mechanism for beckground task (Multi Threading).

And the second way is interviewer have android background then he will check your android and logical skills .This kind of interview is more easy to crack because here an experienced professional face only android technology in that he is expert .

Here I am going to mension some question that usually asked from experienced android professional. I would like to cover thier answers in my next blog currently you take refrence question from here.

1) Difference between serializable and parcelable?

2) Different kind of android services and their details 

3) Difference betweens async task and services?

4) Where to use async task and where servese? he can give some example and ask what we have to use between them?

5) Broad cast receiver ? How many types of broad cast receiver? how to resgister them?

6) What happen when we implement two broad cast receiver in same application which receive same type data?

7) What is stickey broad cast?

8) How to use Assert in android?

9) What happen if you have implement an async task and your orientation has been changed? how to deal with orientation change with async task?

10) What is fragment ? how to deal with android activity and fragmentation? how to deal when oriention is getting change?

11) What is the difference beteen attach() a fragment and replace() a fragment?

12) Differentiate between lounching modes Standard,SingleTop,SingleTask,SingleInstance?

13) How to use content providers ? Implementation details of content provider and their use?

14) What is design patten? which design patters you used in your projects?

15) What is singleton class?

16) Explain how to design an android application?

17) Activity life cycle with practical example?

18) Which activuty life cycle method called when a dialog box is opend?

19) Frangement life cycle methods ? Advantage of fragments?

20) can we create object of interface ? ans: No then next que. what is this  ex .  button.setOnClickListener(new OnClickListener() { }? 
why we are creating object of interface?

21) Explain life cycle method of activity?

22) Explain Life cycle method of services? How many types of services in android?

23) How to establish communication betwwn activity and services?

24) How to do automation testing on your application ? 

25) How many third party library you uesd in your application?

26) what is appcompact ?

27) What is material design ? benefits of material design?

28) What is new in android studio over eclipse?

29) Differnce between eclipse and android studio?

30) How to pass an object from one activity to other?

31) can we extends String class in java?

32) Why string is immutable in java?

33) Thread life cycle ?

34) What is collections ? Difference between various type of collections? 

35) Difference between abstract class and interface?

36) How to increace performance of an android application?

37) how to monitor memory consumption in android app ? and how to reduce it?

38) What happen when we declare two activity as a louncher activity?

39) How to deal with UI with different type of screen size and devices?

These above question is generally used to ask in android inteview questions for an experienced professional and also interviewer genraly check your approach therefore while answering your apporoch must be optimised.

Core JAVA question also used to ask that I am not covering in this blog .I will try to write another blog for this because as I mensioned above first way of interview then the question is different it most probably core java questions.

If I forgot to mension any question so please post questions .