Remote Service Client Example

This example will show you how to handle and invoke remote service from client.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it RemoteServiceClientExample.

2.) Write following into main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/welcome"
    />
<Button android:id="@+id/startButton"
    android:text="@string/startButton"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    </Button>
<Button android:id="@+id/stopButton"
    android:text="@string/stopButton"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    </Button>
<Button android:id="@+id/bindButton"
    android:text="@string/bindButton"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    </Button>
<Button android:id="@+id/releaseButton"
    android:text="@string/releaseButton"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    </Button>
<Button android:id="@+id/invokeButton"
    android:text="@string/invokeButton"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    </Button>
<TextView android:id="@+id/notApplicable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/notApplicable" /> 
<TextView android:id="@+id/serviceStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/serviceStatus" />
</LinearLayout>

3.) Import com.example.remoteserviceexample into src. (check another blogpost RemoteServiceExample for this)
4.) Run for output.

Steps:

1.) Create a project named RemoteServiceClientExample and set the information as stated in the image.

Build Target: Android 4.2
Application Name: RemoteServiceClientExample
Package Name: com. RemoteServiceClientExample
Activity Name: RemoteServiceClientExample
Min SDK Version: 4.2

2.) Open RemoteServiceClientExample.java file and write following code there:

package com.example.remoteserviceclient;
import com.example.remoteserviceexample.IMyRemoteService;
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;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class RemoteServiceClientExample extends Activity {
    private IMyRemoteService remoteService;
    private boolean started = false;
    private RemoteServiceConnection conn = null;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button start = (Button)findViewById(R.id.startButton);
        Button stop = (Button)findViewById(R.id.stopButton);
        Button bind = (Button)findViewById(R.id.bindButton);
        Button release = (Button)findViewById(R.id.releaseButton);
        Button invoke = (Button)findViewById(R.id.invokeButton);
        
        start.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                startService();
            }
        });
        
        stop.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                stopService();
            }
        });      
        
        bind.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                bindService();
            }
        }); 
        
        release.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                releaseService();
            }
        });         
        
        invoke.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                invokeService();
            }
        });         
   
    }
    
    private void startService(){
            if (started) {
                Toast.makeText(RemoteServiceClientExample.this, "Service already started", Toast.LENGTH_SHORT).show();
            } else {
                Intent i = new Intent();
                i.setClassName("com.example.remoteserviceexample", "com.example.remoteserviceexample.RemoteService");
                startService(i);
                started = true;
                updateServiceStatus();
                Log.d( getClass().getSimpleName(), "startService()" );
            }
            
    }
       
    private void stopService() {
            if (!started) {
                Toast.makeText(RemoteServiceClientExample.this, "Service not yet started", Toast.LENGTH_SHORT).show();
            } else {
                Intent i = new Intent();
                i.setClassName("com.example.remoteserviceexample", "com.example.remoteserviceexample.RemoteService");
                stopService(i);
                started = false;
                updateServiceStatus();
                Log.d( getClass().getSimpleName(), "stopService()" );
            }
    }
      
    private void bindService() {
                if(conn == null) {
                    conn = new RemoteServiceConnection();
                    Intent i = new Intent();
                    i.setClassName("com.example.remoteserviceexample", "com.example.remoteserviceexample.RemoteService");
                    bindService(i, conn, Context.BIND_AUTO_CREATE);
                    updateServiceStatus();
                    Log.d( getClass().getSimpleName(), "bindService()" );
                } else {
                    Toast.makeText(RemoteServiceClientExample.this, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
                }
    }
        
    private void releaseService() {
                if(conn != null) {
                    unbindService(conn);
                    conn = null;
                    updateServiceStatus();
                    Log.d( getClass().getSimpleName(), "releaseService()" );
                } else {
                    Toast.makeText(RemoteServiceClientExample.this, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show();
                }
    }
        
    private void invokeService() {
                if(conn == null) {
                    Toast.makeText(RemoteServiceClientExample.this, "Cannot invoke - service not bound", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        int counter = remoteService.getCounter();
                          TextView t = (TextView)findViewById(R.id.notApplicable);
                          t.setText( "Counter value: "+Integer.toString( counter ) );
                          Log.d( getClass().getSimpleName(), "invokeService()" );
                    } catch (RemoteException re) {
                        Log.e( getClass().getSimpleName(), "RemoteException" );
                    }
                }
        }              
      
      class RemoteServiceConnection implements ServiceConnection {
          public void onServiceConnected(ComponentName className,
            IBinder boundService ) {
            remoteService = IMyRemoteService.Stub.asInterface((IBinder)boundService);
            Log.d( getClass().getSimpleName(), "onServiceConnected()" );
          }
          public void onServiceDisconnected(ComponentName className) {
            remoteService = null;
           updateServiceStatus();
           Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
          }
      };
      
      private void updateServiceStatus() {
          String bindStatus = conn == null ? "unbound" : "bound";
          String startStatus = started ? "started" : "not started";
          String statusText = "Service status: "+
                                bindStatus+
                                ","+
                                startStatus;
          TextView t = (TextView)findViewById( R.id.serviceStatus);
          t.setText( statusText );   
        }
      
      protected void onDestroy() {
          super.onDestroy();
          releaseService();
          Log.d( getClass().getSimpleName(), "onDestroy()" );
      }
 }

5.) Compile and build the project.

Output

Image

 

If you are looking for zip project please comment …
Hope it will help you…
Thanks…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s