Monday, July 22, 2013

Creating a Remote Background Service In Android.

How to create a basic Remote Services in Android:

Following article will illustrate how to create a simple basic Remote Service in Android that will run in the background, and which will be triggered by the activity.

Since last so many days I was struggling badly on creating a Remote background service in Android, For the same I found various articles, also went through many blogs, the docs for the android developers etc. Whatever articles I went through, the example given in them had some service task performing, which was confusing me, however I wanted a clear framework and design starting from a strach to implement the background service, and so is this post,

Following atricle will illustrate the basics of creating a Remote Background Service in Android.

The very first step is to create a new Android Project in Eclipse.

Then add the Service Interface in a '.aidl' file.

AIDL  (Android Interface Definition Language) is similar to the java interface with the method signature defined.

Following are the contents of 'RemoteServiceExample.aidl' file:

package com.example;

interface RemoteServiceExample {
      void doServiceTask();
}

Once after creating above file whenever you build the workspace, Eclipse generates the corresponding java interface, you can see the same in the 'gen' section. Also a care is to be taken that this is the autogenerated file and no need to modify the same.


Following is the code for the Core Service implementation:


package com.example;

import android.app.Service;

import android.content.Intent;

package com.example;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; 
import android.os.RemoteException;
import android.util.Log;


public class CoreRemoteService extends Service{
@Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return coreRemoteServiceStub;
}  

private Stub RemoteServiceExample.Stub coreRemoteServiceStub = new RemoteServiceExample.Stub() {
public void doServiceTask() throws RemoteException {
/// Write here, code to be executed in background
Log.d(getClass().getSimpleName(),"Hello World From Remote Service!!");
}   
};

@Override 
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(),"onCreate()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(),"onDestroy()");
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(getClass().getSimpleName(), "onStart()");
}
}


Form the above code have a look at the onBind() method, it returns the IBinder object. IBinder will represent the implementation of the remote service.
The implementation of the method of the 'aidl' interface (doServiceTask() in this example) is provided by the Stub class of the RemoteServiceExample.
In the method doServiceTask() will have the list of all the task to be executed while service is running. It can have the other method calls or the Code blocks to be executed. In the example I'm just printing a single line log "Hello World From Remote Service!!".

Now, coming to the main Activity class which will trigger the service, or we can say that the Activity will act as Client which can connect to the above created service. Have a look at the code for the same as follows:

package com.example;
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;
import android.os.RemoteException;
import android.util.Log;

public class ExampleRemoteService extends Activity {
RemoteServiceExample remoteServiceExample;
private RemoteServiceConnection conn = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        Intent i = new Intent();        
i.setClassName("com.example", "com.example.CoreRemoteService");
startService(i);
conn = new RemoteServiceConnection(); 
bindService(i, conn, Context.BIND_AUTO_CREATE);        
    }       
    class RemoteServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className, IBinder boundService ) {    
         remoteServiceExample = RemoteServiceExample.Stub.asInterface((IBinder)boundService);        
         try{
         remoteServiceExample.doServiceTask();
         }catch(RemoteException e){        
         e.printStackTrace();
         }        
          Log.d( getClass().getSimpleName(), "onServiceConnected()" );
        }

        public void onServiceDisconnected(ComponentName className) {          
   Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
        }
    };
    
}

Here I haven't kept any button to explicitly start the service, instead the service is started as the Activity is created.
An object of Intent is created, where the classname of the same is set, and then this object is passed as an argument of startService() method.
The class name set in the Intent is the fully qualified class name of the Class which extends 'Service', here in the example, 'CoreRemoteService' class.
Now the class 'RemoteServiceConnection' which implements 'ServiceConnection' interface is created to establish the connection with the remote service.
The object of this class along with the Intent object is passed as an argument in bindService() method.

Finally, we need to add a reference of the remote service created in Android Manifest file as follows:



Now you are done with creating the remote background service.

As you install the apk and run on an Android Device or Emulator, service Prints in the log "Hello World From Remote Service!!".

Also you can check in your device, Settings>Applications>Running Service, the name of your service in the running services list.

So this was the very basic example of creating a remote background service in Android.

Thats all from my end!

Happy Coding!! :-))

Saturday, July 20, 2013

Android Detect Internet Connection Status

     

 It is better to check internet connectivity status before making any HTTP Requests to avoid http exceptions. This tutorial will explain how to detect internet connection status in your applications.

Create new Project

1. Create a new project in Eclipse IDE by filling required details. File ⇒ New ⇒ Android Project
2. After creating new project first step is to add required permission in yourAndroidManifest.xml file.
To access internet we need INTERNET Permission
To detect network status we need ACCESS_NETWORK_STATE Permission
AndroidManifest.xml
xml version="1.0" encoding="utf-8"?>
    package="com.example.detectinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidDetectInternetConnectionActivity"
            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" />
    
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
3. Create a new Class file and name it as ConnectionDetector.java and type the following code.
ConnectionDetector.java
package com.example.detectinternetconnection;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
     
    private Context _context;
     
    public ConnectionDetector(Context context){
        this._context = context;
    }
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
          }
          return false;
    }
}
4. When ever you want to check Internet Status in your application callisConnectingToInternet() function and it will return true or false
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false
5. In this tutorial for testing purpose i placed a simple button. Once you press the button it will show appropriate alert message about internet connection status.
6. Open your main.xml under res/layout folder and create a button.
main.xml
xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Detect Internet Status" />
     
    <Button android:id="@+id/btn_check"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check Internet Status"
        android:layout_centerInParent="true"/>
</RelativeLayout>
7. Finally open your MainActivity file and paste the following code. In the following code i showed an alert dialog with respected internet status message.
package com.example.detectinternetconnection;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AndroidDetectInternetConnectionActivity extends Activity {
    // flag for Internet connection status
    Boolean isInternetPresent = false;
     
    // Connection detector class
    ConnectionDetector cd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btnStatus = (Button) findViewById(R.id.btn_check);
        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        btnStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // get Internet status
                isInternetPresent = cd.isConnectingToInternet();
                // check for Internet status
                if (isInternetPresent) {
                    // Internet Connection is Present
                    // make HTTP requests
                    showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",
                            "You have internet connection", true);
                } else {
                    // Internet connection is not present
                    // Ask user to connect to Internet
                    showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection",
                            "You don't have internet connection.", false);
                }
            }
        });
    }
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     * */
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        // Setting Dialog Title
        alertDialog.setTitle(title);
        // Setting Dialog Message
        alertDialog.setMessage(message);
         
        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }
}
Run and test your application. For the above you will be getting following outputs.
android test internet connectivity
android test internet connectivity no intenet