Showing posts with label Background Work. Show all posts
Showing posts with label Background Work. Show all posts

Thursday, October 24, 2013

Volley Android Networking Library : How to use Volley in your application and why?

In 2013 I/O Android session Ficus Kirkpatrick launched a new support for android developer. This is really cool library for networking operation.
If being android developer you stuck and searching for many question's answer related networking connection. Volley android sdk Gives the answer

Volley fixed these problems

1) All network requests happen serially
2) Rotating the screen will reload everything from the network
3) AsyncTasks stomp on recycled views
4) Compatibility problems on Froyo

Then curiously how's the documentation of android volley going to be !!Answer is Very simple

Volley Android library Implementation


Initializing Volley android before use anywhere in Constructer which called very first time


 // Somewhere common; app startup or adapter constructor  
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());

Making request to URL which gives Json Response


 mRequestQueue.add(new JsonObjectRequest(Method.GET, url, null,  
new Listener<JSONObject>() {
public void onResponse(JSONObject jsonRoot) {
mNextPageToken = jsonGet(jsonRoot, "next", null);
List<Items> items = parseJson(jsonRoot);
appendItemsToList(item);
notifyDataSetChanged();
}
}
}

Image Loading through volley contain two way

  •  Using ImageLoader class
 mImageLoader.get(image_url,imageView, R.drawable.loading, R.drawable.error);  
  • Using Volley Android Custom ImageView
 - <ImageView  
+ <com.android.volley.NetworkImageView
Java mImageView.setImageUrl(BASE_URL + item.image_url, mImageLoader);

There are a lot more in Volley android. Download Sample and check them out

Wednesday, March 13, 2013

Binding service using Android Interface DefinitionLanguage (.aidl) in android

Binding service using iBinder an Messanger already discussesd. Third and most complicated way is binding service using Android Interface Definition Language (AIDL). Its rarely use and hard to implement. So this post simply will show you how to create one connection using Android Interface Definition Language (AIDL) between activity and service

 When to use Android Interface Definition Language (AIDL)

Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Knowledge Required you should read about binding service using IBinder and Messanger

 Steps 1) create .aidl interface. Create one file name IRemoteService.aidl and keep inside your main package


 // IRemoteService.aidl  
package com.example.locationmanager;
// Declare any non-default types here with import statements
/** Example service interface */
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}

When you build your application IRemoteService.aidl changes into IRemoteService.java like this. You can find this inside bin folder

 // Declare any non-default types here with import statements  
 /** Example service interface */  
public interface IRemoteService extends android.os.IInterface {
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements
com.example.locationmanager.IRemoteService {
private static final java.lang.String DESCRIPTOR = "com.example.locationmanager.IRemoteService";
/** Construct the stub at attach it to the interface. */
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an
* com.example.locationmanager.IRemoteService interface, generating a
* proxy if needed.
*/
public static com.example.locationmanager.IRemoteService asInterface(
android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.example.locationmanager.IRemoteService))) {
return ((com.example.locationmanager.IRemoteService) iin);
}
return new com.example.locationmanager.IRemoteService.Stub.Proxy(
obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data,
android.os.Parcel reply, int flags)
throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getPid: {
data.enforceInterface(DESCRIPTOR);
int _result = this.getPid();
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_basicTypes: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
long _arg1;
_arg1 = data.readLong();
boolean _arg2;
_arg2 = (0 != data.readInt());
float _arg3;
_arg3 = data.readFloat();
double _arg4;
_arg4 = data.readDouble();
java.lang.String _arg5;
_arg5 = data.readString();
this.basicTypes(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements
com.example.locationmanager.IRemoteService {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
/**
* Request the process ID of this service, to do evil things with
* it.
*/
@Override
public int getPid() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getPid, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
/**
* Demonstrates some basic types that you can use as parameters and
* return values in AIDL.
*/
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, java.lang.String aString)
throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(anInt);
_data.writeLong(aLong);
_data.writeInt(((aBoolean) ? (1) : (0)));
_data.writeFloat(aFloat);
_data.writeDouble(aDouble);
_data.writeString(aString);
mRemote.transact(Stub.TRANSACTION_basicTypes, _data,
_reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_getPid = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
/** Request the process ID of this service, to do evil things with it. */
public int getPid() throws android.os.RemoteException;
/**
* Demonstrates some basic types that you can use as parameters and return
* values in AIDL.
*/
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, java.lang.String aString)
throws android.os.RemoteException;
}

Step 2) Implement IRemoteService.aidl inside your service. So first create one service class name AidlService.java here

 import android.app.Service;  
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AidlService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder.asBinder();
}
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
@Override
public int getPid() throws RemoteException {
return 0;
}
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString)
throws RemoteException {
}
};
}

Step 3) ServiceConnection class allow to create connection between IRemoteService and your service class. So bind your service inside your activity. Change your main activity code to as follows

 import android.app.Activity;  
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
public class BindAidlActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindService();
}
public void bindService() {
Intent intent = new Intent(this, AidlService.class);
bindService(intent, new ConnectService(), Context.BIND_AUTO_CREATE);
}
public void stoppingService() {
Intent intent = new Intent(this, AidlService.class);
stopService(intent);
}
IRemoteService uAidlService;
public class ConnectService implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
uAidlService = IRemoteService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
/**
* Called when service disconnected
*/
}
}
}

Download All Service Binding Example

Saturday, August 4, 2012

Updating UI from background service in android

Its recommended that always perform long task using background Thread or Service. If you have not idea how to create basic service and Thread then please read these

Now back to some current one, we can perform any long task in background using service. Let you are downloading movies in your application and we run one service to start download. But if we did not notify about this to user then end user will think that application is not responsive. We can not  update User interface from service directly to show progress in android.

so if you are using service in your android application , two step will make sure update of user interface when ever new data loaded inside service

  •  Create one service from activity 
  • Then bind this service to activity using service connection 
Remember These some points about service 
  1. Service will not create new instance if it is already running
  2. When you bind service it will call onserviceConnected() method
  3. You can not unbind or bind service if it is already stopped (either explicitly or implicitly)
Service connection will be perform using Binder. Whenever you will bind service it will call connected method of service connection. in this method we will get Service class object, and our work done. Using object of service we can use any updated value from service class

   LocalService localservice
;
  
ServiceConnection serviceConnection = new ServiceConnection() {

      
@Override
      
PUBLIC void onServiceDisconnected(ComponentName name) {
           txt_view.setText
("DisConnected !!!!! bind it for updating UI...";
      
}

      
@Override
      
PUBLIC void onServiceConnected(ComponentName name, IBinder SERVICE) {
           localservice
= ((LocalService.LocalBinder) SERVICE).getBinder();
          
try {
               txt_view.setText
(String.valueOf(localservice.STR));
              
localservice.STR = "String changes from Activit"
           } catch
(Exception e) {
           }
       }
   }
;}


In service class we will create a Binder to return the object of current service.

   @Override
  
PUBLIC IBinder onBind(Intent intent) {
      
RETURN iBinder;
  
}

   private IBinder iBinder
= new LocalBinder();

  
PUBLIC class LocalBinder extends Binder {
       LocalService getBinder
() {
          
RETURN LocalService.this;
      
}
   }


Here onBind() will return service class object when service will connected . I have taken a string inside the service and set to TextView's background .

on calling bindservice() onserviceConnected() will call. But it onServiceDisconnected() will never call either you call unbind service or stop service. It will only call when service will stop stopped in memory low situation or by OS. once service disconnected, you will not get receive result any more

     
Service Main Screen
  This screen have only simple UI for starting , binding, unbinding and stopping service. I started the service     

   private Intent intent = NULL;
  
private OnClickListener startService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
           intent
= new Intent(MainActivity.this,      

                LocalService.class);
           startService(intent);
      
}
     }
;


It start the service. Now we will bind study how bind and unbind service

Binding Sevice....while binding service we will user ServiceConnection class object

   private OnClickListener boundService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               bindService
(intent, serviceConnection, BIND_AUTO_CREATE);
          
} ELSE {
               Toast.makeText
(MainActivity.this,
                      
"First Satrt service to bind." Toast.LENGTH_LONG)
                      
.show();
          
}
       }
   }
;
  
private OnClickListener unboundService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               unbindService
(serviceConnection);
              
txt_view.setText("DisConnected !!!!! bind it for updating UI...";
          
} ELSE {
               Toast.makeText
(MainActivity.this,
                      
"First Satrt bind to UnBind." Toast.LENGTH_LONG)
                      
.show();
          
}
       }
   }
;
  
private OnClickListener stopService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               stopService
(intent);
          
} ELSE {
               Toast.makeText
(MainActivity.this, "First Satrt to stop it."
                       Toast.LENGTH_LONG
).show();
          
}
       }
   }
;


Now see some screen shot to get idea how this will work..

        Android trainner
        Service Disconnected After Unbind
                                     
                    Activity Showed value from Service   


Now i think you got some idea how we can update UI from background service
Download source cod to read complete piece of code

 Download All Service Binding Example                                                     

Sunday, June 10, 2012

Checking network connection and performing operation in Thread

My this post is related to checking network connection  and how to handle if network connection is not available to make our application more responsive. Later on we will learn how to perform time taking operation in separate thread if connection is present.

First of all we two permission if your are checking wifi connection then you need one extra permission

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you want to check connection on click of particular button you can  call this function inside click listener of button

public void ahmadNetworkHanlder() {
 
ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService
(Context.CONNECTIVITY_SERVICE);
   
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
   
if (networkInfo != null && networkInfo.isConnected()) {
       
// fetch data here as network is availble
   
} else {
       
// display error dialog to notify user ,connection is not present
   
}
}
Now consider case, Network is available. Use one asynchronous task to perform network operation like downloading data



public class AhmadActivity extends Activity {
   
private static final String DEBUG_TAG = "AhmadHttp";
   
private EditText urlText;
   
private TextView textView;
   
   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.main);  
        urlText
= (EditText) findViewById(R.id.myUrl);
        textView
= (TextView) findViewById(R.id.myText);
   
}
// Call this method on Click of A button
  public void ahmadNetworkHandler() {
       
// Gets the URL from the UI's text field.
       
String stringUrl = urlText.getText().toString();
       
ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService
(Context.CONNECTIVITY_SERVICE);
       
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
       
if (networkInfo != null && networkInfo.isConnected()) {
           
new DownloadWebpageText().execute(stringUrl);
       
} else {
            textView
.setText("No network connection available.");
       
}
   
} /* Here we take thread to down load image etc

     
private class DownloadWebpageText extends AsyncTask {
       
@Override
       
protected String doInBackground(String... urls) {
             
           
// params comes from the execute() call: params[0] is the url.
           
try {
               
return downloadUrl(urls[0]);
           
} catch (IOException e) {
               
return "Unable to retrieve web page. URL may be invalid.";
           
}
       
}
       
// onPostExecute displays the results of the AsyncTask.
       
@Override
       
protected void onPostExecute(String result) {
            textView
.setText(result);
       
}
   
}
}
Now we almost complete our task. Just we need to create a function that will handle download from url. So here is the final function


/* we pass the url from asynchronous task */

private String downloadUrl(String myurl) throws IOException {
   
InputStream is = null;
 
  int len = 500;
   
try {
        URL url
= new URL(myurl);
       
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn
.setReadTimeout(10000 /* milliseconds */);
        conn
.setConnectTimeout(15000 /* milliseconds */);
        conn
.setRequestMethod("GET");
        conn
.setDoInput(true);
       
// Starts the query
        conn
.connect();
       
int response = conn.getResponseCode();
       
Log.d(DEBUG_TAG, "The response is: " + response);
       
is = conn.getInputStream();

       
// Convert the InputStream into a string See this Link
       
String contentAsString = readIt(is, len);
       
return contentAsString;
       
   
// Makes sure that the InputStream is closed after the app is
   
// finished using it.
   
} finally {
       
if (is != null) {
           
is.close();
       
}
   
}
}

So its done. Now you have string response you can do anything what your requirement tell you to do. 

Sunday, April 15, 2012

Asynchronous task, Updating UI from background in android

As all we know in android there are two ways to perform background task such as downloading image and other task that include long operation
  • Using Thread 
  • Asynchronous Task                          
Using Thread, there is one dis-advantage that we can not update user interface other wise we will get Looper.loop() exception

So its efficient to use Asynchronous task.
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.


Let take one example of downloading images from URL's Array.So body of Asynchronous task 's body will be like this


 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     
protected Long doInBackground(URL... urls) {
         
int count = urls.length;
         
long totalSize = 0;
         
for (int i = 0; i < count; i++) {
             totalSize
+= Downloader.downloadFile(urls[i]);
             publishProgress
((int) ((i / (float) count) * 100));
         
}
         
return totalSize;
     
}

     
protected void onProgressUpdate(Integer... progress) {
         setProgressPercent
(progress[0]);
     
}

     
protected void onPostExecute(Long result) {
         showDialog
("Downloaded " + result + " bytes");
     
}
 
}
 
    Like Thread we can create asynchronous task like this

 new DownloadFilesTask().execute(url1, url2, url3);
    Now asynchronous has three generic type.Let have a look on their requirement 
    


  • Params, the type of the parameters sent to the task upon execution.
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation.

  •     
    But its not necessary to use all type.you can set like this if you do not want to use 

    private class MyTask extends AsyncTask<Void, Void, Void> { ... }
     Now it has four step -

    1)  onPreexecute() -Before it start executing it call this method .It call before it goes to perform task in background so we can display a ProgressDialog here )doInBackground() - perform long background task here

    3)onProgressUpdate() - Update your progress of dialog to show to user

    4)onPostExecute() - Post or show your result here .Dismiss progress dialog  box here
    There are a few threading rules that must be followed for this class to work properly:
    • The task instance must be created on the UI thread.
    • execute(Params...) must be invoked on the UI thread.
    • Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
    • The task can be executed only once (an exception will be thrown if a second execution is attempted.)
    Posting Lama ►
     

    Copyright 2013 Tutorials For Newbie: Background Work Template by CB Blogger Template. Powered by Blogger