Tuesday, December 31, 2013

Android Loaders

Loaders in Android

Introduction with Honeycomb
Where we can use?
1) to access data of databases 2) content providers

They load data asynchronously and notify the listeners when the results are available/ready.

characteristics:
  • They are available to every Activity and Fragment.
  • They provide asynchronous loading of data.
  • They monitor the source of their data and deliver new results when the content changes.
  • They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.


the main classes and interfaces are as folllows


1)LoaderManager = Manages your Loaders for you. Responsible for dealing with the Activity or Fragment lifecycle


2)Loader =The base class for all Loaders


3)LoaderManager.LoaderCallbacks = A callback interface you must implement


4)AsyncTaskLoader = An implementation that uses an AsynTask to do its work


5)CursorLoader = A subclass of AsyncTaskLoader for accessing ContentProvider data


eXample


please visit at github




and


https://github.com/emil10001/AndroidSerialSQL/tree/sample (Source code)

Advantage==>  Loaders in Android are great, they allow us to asynchronously load data to be used in Adapters. It is found that CursorLoaders very useful for getting data from a database to the UI in a way that minimizes blocking calls on the UI thread.

Google did not only introduce Loaders but also deprecated the previous way to handle a Cursor within your activities. You shouldn’t use startManagingCursor()or managedQuery() in your projects anymore.





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)


Wednesday, September 25, 2013

using IBinder class to Bind service

There are total 3 ways to bind a service with application components
  1. Using IBinder class
  2. Using Messanger class
  3. Using AIDL
The life is a process of learning even after some bad happening we are going on and learning things. someone asked me about the Binding Services and i was unable to answer  and that after i tried to work on the same.

Create a project and have a main activity with Name MainActivity.

Implementing the Binder

to implement the binder creat a class SomeServic which extends Service class, i create an inner class with name LocalBinder which is inner class and inside SomeService.

package com.example.bindserviceusingbinderclass;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class SomeService extends Service {

IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

public class LocalBinder extends Binder {
public SomeService getServerInstance() {
return SomeService.this;
}
}

public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
}


finally we need to start service at Mainactivity

Binding the Client to the Service

package com.example.bindserviceusingbinderclass;

import com.example.bindserviceusingbinderclass.SomeService.LocalBinder;

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

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends Activity {

boolean mBounded;
SomeService mServer;
TextView text;
Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
text.setText(mServer.getTime());
}
});
}

@Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, SomeService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};

ServiceConnection mConnection = new ServiceConnection() {

public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
mBounded = false;
mServer = null;
}

public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder) service;
mServer = mLocalBinder.getServerInstance();
}
};

@Override
protected void onStop() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
@Override
protected void onDestroy() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
}


do not forget to work with manifest for the service.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bindserviceusingbinderclass"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bindserviceusingbinderclass.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".SomeService" />
    </application>
    

</manifest>

the activity_main.xml looks like

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/text"
        android:layout_below="@+id/text"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="54dp"
        android:text="Button" />

</RelativeLayout>



Wednesday, June 26, 2013

Android Downloading MP3 to sd card

Some guy asked me the question regarding to how to download the mp3 files to the sd card and i wrote the program for this purpose please have a look and enjoy the practices.

Create a project with the name DownloadMp3 and have a main activity with following code

package com.jitesh.downloadmp3;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private static String fileName = "file.mp3";
private static final String MY_URL = "http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3";

private Button play;
private TextView message;

private ProgressDialog pDialog;

// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

play = (Button) findViewById(R.id.download);
message=(TextView)findViewById(R.id.message);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new DownloadFileFromURL().execute(MY_URL);
}
});

}

/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

public void downloadStreams() {
try {
URL url = new URL(MY_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.e("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: ");
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

/**
* Downloading file in background thread
* */
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);

// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/"
+ fileName);

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));

// writing data to file
output.write(data, 0, count);
}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}

/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);

// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + fileName;
// setting downloaded into image view
// my_image.setImageDrawable(Drawable.createFromPath(imagePath));
message.setText("File downloaded and saved to directory==>"+imagePath);
}

}
}


the main layout file is presented here which is activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download" >
    </Button>

</RelativeLayout>

the strings.xml is having following attributes

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DownloadMp3</string>
    <string name="hello_world">please click the button to download the stream!</string>
    <string name="menu_settings">Settings</string>

</resources>


the manifest should have following permissions

<uses-permission android:name="android.permission.INTERNET" />
     
    <!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and it should look like below given manifest attributes

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jitesh.downloadmp3"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jitesh.downloadmp3.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        
    </application>
<uses-permission android:name="android.permission.INTERNET" />
     
    <!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

the screenshots are given below



Also the source code can be downloaded from http://www.mediafire.com/download/18axcocxot725pl/DownloadMp3.zip