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();
    }
  }
}


4 comments: