Tuesday, October 29, 2013

Android using Singleton






Java Singleton Class Example Using Private Constructor

  • We can make constructor as private. So that We can not create an object outside of the class.
  • This property is useful to create singleton class in java.
  • Singleton pattern helps us to keep only one instance of a class at any time.
  • The purpose of singleton is to control object creation by keeping private constructor.


=====> the main class
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package designpattern;

/**
 *
 * @author jiteshupadhyay
 */
public class DesignPattern {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Singleton tmp = Singleton.getInstance();
        tmp.demoMethod();
        

    }

}


===>the singleton class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package designpattern;

/**
 *
 * @author jiteshupadhyay
 */
public class Singleton {
    
private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}





Saturday, October 26, 2013

Breaking and android applications APk file (a reverse engineering )

Procedure for decoding .apk files, step-by-step method:

Step 1:

Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg.: rename from filename.apk to filename.apk.zip) and save it. Now you get classes.dex files, etc. At this stage you are able to see drawable but not xml and java files, so continue.

Step 2:

Now extract this zip apk file in the same folder (or NEW FOLDER). Now download dex2jar from this linkhttp://code.google.com/p/dex2jar/ and extract it to the same folder (or NEW FOLDER). Now open command prompt and change directory to that folder (or NEW FOLDER). Then write dex2jar classes.dex and press enter. Now you get classes.dex.dex2jar file in the same folder. Then download java decompiler from http://java.decompiler.free.fr/?q=jdgui and now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. At this stage you get java source but the xml files are still unreadable, so continue.

Step 3:

Now open another new folder and put these files
  1. put .apk file which you want to decode
  2. download apktool v1.x AND apktool install window (both can be downloaded at the same location) and put in the same folder
  3. download framework-res.apk file and put in the same folder (Not all apk file need framework-res.apk file)
  4. Open a command window
  5. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
  6. apktool d "fname".apk ("fname" denotes filename which you want to decode)
now you get a file folder in that folder and now you can easily read xml files also.

Friday, October 25, 2013

Something about AAPT(Android asset packaging tool)

the given diagram is about a build process of android apps.

Android Asset Packaging Tool (AAPT) -
 
Constructs the Android package files (.apk). 

This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.
A Detailed Look at the Build Process

The general process for a typical build is outlined below:

  • The Android Asset Packaging Tool (aapt) takes your application resource files, such as the AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is also produced so you can reference your resources from your Java code.
  • The aidl tool converts any .aidl interfaces that you have into Java interfaces.
  • All of your Java code, including the R.java and .aidl files, are compiled by the Java compiler and .class files are output.
  • The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and .class files that you have included in your project are also converted into .dex files so that they can be packaged into the final .apk file.
  • All non-compiled resources (such as images), compiled resources, and the .dex files are sent to the apkbuilder tool to be packaged into an .apk file.
  • Once the .apk is built, it must be signed with either a debug or release key before it can be installed to a device.
  • Finally, if the application is being signed in release mode, you must align the .apk with the zipalign tool. Aligning the final .apk decreases memory usage when the application is running on a device

MVP in android (Model View Presenter)


Model-View-Presenter pattern fit s for android 

  • serving as an entry point
  • rendering the  components
  • routing user events to the presenter
This allows us to implement our model like :
View - this contains UI components, and handles events for them.
Presenter - this will handle communication between model and view, it as a gateway to the model. Meaning, if we have a complex domain model representing, god know what, and our view only needs a very small subset of this model, the presenters job is to query the model and then update the view.
Model - this should basically be full domain model, hopefully it will help making your domain model more "tight" as well, since we wont need special methods to deal with cases

MVP separates the UI concerns between the data of the UI (Model), the display of the UI (View), and the logic of the UI (Presenter). For Android, the View is the Activity, which will handle gathering user input and updating the display; the Presenter is a class that will handle communication between the Model and View; the Model will handle persisting and retrieving data, along with any business logic that the data must adhere to. Interfaces will be used to de-couple each of these components 


MVC in android




There is no universally unique MVC pattern in android . MVC is a concept rather than a solid programming framework, so it is about conceptual understanding of MVC. We can implement our own MVC in any platforms. As long as we stick to the following basic idea, we are implementing MVC:
  • Model: What to render
  • View: How to render
  • Controller: Events, user input
we can say MVC is already implemented in Android as:
  1. View = layout, resources and built-in classes like Button derived from android.view.View.
  2. Controller = Activity
  3. Model = the classes that implement the application logic
Also we can  think about this way, when we program our model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, we don't care our rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform specific rendering code.
This is particularly useful when you use Mono to share the model in order to develop cross platform applications.
  • You define your user interface in various XML files by resolution/hardware etc.
  • You define your resources in various XML files by locale etc.
  • You extend clases like ListActivityTabActivity and make use of the XML file by inflaters
  • You can create as many classes as you wish for your model
  • A lot of Utils have been already written for you. DatabaseUtils, Html,
Please visit the Blog for information.

Tuesday, October 15, 2013

Special cases When the Services running in the background can be destroy?


 Services should carry out long running operations indefinitely, they are fated to be killed by the Android android system, if they are running in the back-ground.  

This is how it happens: 

 1) When a Service starts, it runs in the main process: A service when created does not create a separate thread/process for itself (unless instructed to do so); instead, it runs in the main thread of the running application, thus consuming the memory resources of the main system. 

 2) What happens in case of low system memory? The system would choose to close the components that are low priority, but are still consuming the system resources. Thus, the background components not in user focus are the first ones the system kills. Therefore, it would destroy the services running in the background. This is to free system resources for more important components (Example: for the activity in the foreground interacting with the user).

  3) Does system follow a pattern while killing services to free resources? Yes it does! Read on to find out:  a) Unbound Service: Over time, the system pushes down a long-running service to lower priority in the list of background tasks, and this service is more likely to close first (if unbound), when memory shortage occurs.  b) Services bound to foreground activity: The services that are bound to an activity or any other application component running in the foreground are less likely to be killed than an unbound activity.  c) Foreground Services: The system would never kill a service if it were declared to run in the foreground. We would discuss more about this in later Android tutorials. Stay put!  

4) How to keep a Service from being killed? a) You can create separate threads while creating services for the services to run. Thus, there is reduced consumption of main application memory, and the likelihood of the service being destroyed due to memory shortage is lower than otherwise.  b) As discussed before, you can declare a Service to run in the foreground. This can prevent the system from killing the Service

Difference between bound and unbound service in Android

Android Bound Service and Unbound Service run in Background Android Services is used to do any background task in current activity.There is two types of Services available in android.Service class is responsible for using Services in android for that we need to extends Services class in out Custom service. 

 Bound Service :Service which call indefinitely in between activity 
An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself. 

Unbound Service :Service which call at the life span of calling activity 
In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.

Services has different life cycle from Activity. Services has different method for their life cycle which is startService(),stopService(),onBindService()  



Monday, October 14, 2013

Android Application class and it's use

 The Application class is  in the Android api and according to the class name it's used for global settings or running entrance.
We can specify its name in your AndroidManifest.xml's tag
1
<application android:icon="@drawable/icon" 
android:label=
"@string/app_name" android:name="MyApplication">
We can create our own subclass of Application like this:
public class MyApplication extends Application {
 
       @Override
       public void onConfigurationChanged(Configuration newConfig) {
           super.onConfigurationChanged(newConfig);
        }
 
      @Override
       public void onCreate() {
                super.onCreate();
       }
 
      @Override
       public void onLowMemory() {
             super.onLowMemory();
    }
 
      @Override
       public void onTerminate() {
             super.onTerminate();
    }
 
}



Application level callbacks

  • onConfigurationChanged( ) Called by the system when the device configuration changes while your component is running.
  • onCreate( ) Called when the application is starting, before any other application objects have been created.
  • onLowMemory( ) This is called when the overall system is running low on memory, and would like actively running processes to tighten their belts.
  • onTerminate( ) This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.


    
    

An eye over Google Cloud Messaging (GCM)