Ch08 Listings

satya - Saturday, February 27, 2010 8:02:20 PM

Listing 8-1


<service android:name="StockQuoteService">
      <intent-filter>
            <action android:name="com.androidbook.stockquoteservice.IStockQuoteService" />
      </intent-filter>
</service>

satya - Saturday, February 27, 2010 8:02:57 PM

Listing 8-2


HttpGet method = new HttpGet("http://somehost/WS2/Upload.aspx?one=valueGoesHere");
client.execute(method);

satya - Saturday, February 27, 2010 8:03:22 PM

Listing 8-3


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class TestHttpPost
{
    public String executeHttpPost() throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(
                    "http://somewebsite/WS2/Upload.aspx");

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("one", "valueGoesHere"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);

            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

satya - Saturday, February 27, 2010 8:04:01 PM

Listing 8-4


import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

public class TestMultipartPost extends Activity
{
    public void executeMultipartPost()throws Exception
    {

        try {
            InputStream is = this.getAssets().open("data.xml");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = 
             new HttpPost("http://192.178.10.131/WS2/Upload.aspx");

            byte[] data = IOUtils.toByteArray(is);

            InputStreamBody isb = new InputStreamBody(new 
ByteArrayInputStream(data),"uploadedFile");
            StringBody sb1 = new StringBody("someTextGoesHere");
            StringBody sb2 = new StringBody("someTextGoesHere too");

            MultipartEntity multipartContent = new MultipartEntity();
            multipartContent.addPart("uploadedFile", isb);
            multipartContent.addPart("one", sb1);
            multipartContent.addPart("two", sb2);

            postRequest.setEntity(multipartContent);
            HttpResponse res =httpClient.execute(postRequest);
            res.getEntity().getContent().close();
        } catch (Throwable e)
        {
            // handle exception here
         }
    }
}

satya - Saturday, February 27, 2010 8:04:28 PM

Listing 8-5


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class TestHttpGet {

    public String executeHttpGetWithRetry() throws Exception {
        int retry = 3;

        int count = 0;
        while (count < retry) {
            count += 1;
            try {
                String response = executeHttpGet();
                /**
                 * if we get here, that means we were successful and we can
                 * stop.
                 */
                return response;
            } catch (Exception e) {
                /**
                 * if we have exhausted our retry limit
                 */
                if (count < retry) {
                /**
                 * we have retries remaining, so log the message and go
                * again.
                */
                System.out.println(e.getMessage());
                } else {
                    System.out.println("could not succeed with retry...");
                    throw e;
                }
            }
        }
        return null;
    }

    public String executeHttpGet() throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("http://code.google.com/android/"));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

satya - Saturday, February 27, 2010 8:04:59 PM

Listing 8-6


// ApplicationEx.java
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Application;
import android.util.Log;

public class ApplicationEx extends Application
{
    private static final String TAG = "ApplicationEx";
    private HttpClient httpClient;

    @Override
    public void onCreate()
    {
        super.onCreate();

        httpClient = createHttpClient();

    }

    @Override
    public void onLowMemory()
    {
        super.onLowMemory();
        shutdownHttpClient();
    }

    @Override
    public void onTerminate()
    {
        super.onTerminate();
        shutdownHttpClient();
    }


    private HttpClient createHttpClient()
    {
        Log.d(TAG,"createHttpClient()...");
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);

    
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", 
       PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", 
        SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new 
         ThreadSafeClientConnManager(params,schReg);

        return new DefaultHttpClient(conMgr, params);
    }

    public HttpClient getHttpClient() {
        return httpClient;
    }

    private void shutdownHttpClient()
    {
        if(httpClient!=null && httpClient.getConnectionManager()!=null)
        {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

satya - Saturday, February 27, 2010 8:05:36 PM

Listing 8-6-b


// HttpActivity.java

import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class HttpActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Log.d("ServicesDemoActivity", "a debug statement");
        getHttpContent();
    }
    public void getHttpContent()
    {
        try {
            ApplicationEx app = (ApplicationEx)this.getApplication();
            HttpClient client = app.getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("http://www.google.com/"));
            HttpResponse response = client.execute(request);

            String page=EntityUtils.toString(response.getEntity());
            System.out.println(page);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

satya - Saturday, February 27, 2010 8:05:57 PM

Listing 8-7


import android.app.Service;
public class TestService1 extends Service
{
    private static final String TAG = "TestService1";


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

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return null;
    }
}

satya - Saturday, February 27, 2010 8:06:13 PM

Listing 8-7 xml


// service definition entry: must go in the AndroidManifest.xml file as
// a child of <application>.
<service android:name="TestService1"></service>

satya - Saturday, February 27, 2010 8:07:04 PM

Listing 8-8


Application  getApplication();
abstract IBinder  onBind(Intent intent);
void onConfigurationChanged(Configuration newConfig);
void    onCreate();
void    onDestroy();
void    onLowMemory();
void    onRebind(Intent intent);
void    onStart(Intent intent, int startId);
boolean  onUnbind(Intent intent);
final void      setForeground(boolean isForeground);
final void      stopSelf();
final void      stopSelf(int startId);
final boolean   stopSelfResult(int startId);

satya - Saturday, February 27, 2010 8:07:45 PM

Listing 8-9 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  android:id="@+id/bindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bind"
    />

    <Button android:id="@+id/unbindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UnBind"
    />
</LinearLayout>

satya - Saturday, February 27, 2010 8:08:12 PM

Listing 8-9-a


// BackgroundService.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class BackgroundService extends Service
{
    private NotificationManager notificationMgr;

    @Override
    public void onCreate() {
        super.onCreate();

        notificationMgr =(NotificationManager)getSystemService(
       NOTIFICATION_SERVICE);

        displayNotificationMessage("starting Background Service");

        Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
        thr.start();

    }

    class ServiceWorker implements Runnable
    {
        public void run() {
            // do background processing here...
        
            // stop the service when done...
            // BackgroundService.this.stopSelf();
        }
    }

    @Override
    public void onDestroy()
    {
        displayNotificationMessage("stopping Background Service");
        super.onDestroy();

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }

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

    private void displayNotificationMessage(String message)
    {

        Notification notification = new Notification(R.drawable.note, 
message,System.currentTimeMillis());

        PendingIntent contentIntent = 
PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        notification.setLatestEventInfo(this, "Background Service",message, 
contentIntent);

        notificationMgr.notify(R.id.app_notification_id, notification);
    }
}

satya - Saturday, February 27, 2010 8:08:57 PM

Listing 8-9-b


// MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
    private static final String TAG = "MainActivity";


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

        Log.d(TAG, "starting service");

        Button bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                startService(new Intent(MainActivity.this,
                        BackgroundService.class));
            }});

        Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                stopService(new Intent(MainActivity.this,
                        BackgroundService.class));
            }});

    }
}

satya - Saturday, February 27, 2010 8:09:24 PM

Listing 8-10


// This file is IStockQuoteService.aidl
package com.androidbook.stockquoteservice;
interface IStockQuoteService
{
        double getQuote(String ticker);
}

satya - Saturday, February 27, 2010 8:09:52 PM

Listing 8-11


/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: C:\\android\\StockQuoteService\\src\\com\\androidbook\\stockquoteservice\\�??
IStockQuoteService.aidl
 */
package com.androidbook.stockquoteservice;
import java.lang.String;
import android.os.RemoteException;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Binder;
import android.os.Parcel;
public interface IStockQuoteService extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.androidbook.stockquoteservice.IStockQuoteService
{
private static final java.lang.String DESCRIPTOR = "com.androidbook.stockquoteservice.IStockQuoteService";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
 * Cast an IBinder object into an IStockQuoteService interface,
 * generating a proxy if needed.
 */
public static com.androidbook.stockquoteservice.IStockQuoteService asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.androidbook.stockquoteservice.IStockQuoteService))) {
return ((com.androidbook.stockquoteservice.IStockQuoteService)iin);
}
return ((com.androidbook.stockquoteservice.IStockQuoteService)iin);
}
return new com.androidbook.stockquoteservice.IStockQuoteService.Stub.Proxy(obj);
}
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_getQuote:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
double _result = this.getQuote(_arg0);
reply.writeNoException();
reply.writeDouble(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.androidbook.stockquoteservice.IStockQuoteService
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
public double getQuote(java.lang.String ticker) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
double _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(ticker);
mRemote.transact(Stub.TRANSACTION_getQuote, _data, _reply, 0);
_reply.readException();
_result = _reply.readDouble();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_getQuote = (IBinder.FIRST_CALL_TRANSACTION + 0);
}
public double getQuote(java.lang.String ticker) throws android.os.RemoteException;
}

satya - Saturday, February 27, 2010 8:10:15 PM

Listing 8-12


// StockQuoteService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class StockQuoteService extends Service
{
    private static final String TAG = "StockQuoteService";
	    public class StockQuoteServiceImpl extends IStockQuoteService.Stub
    {
        @Override
        public double getQuote(String ticker) throws RemoteException
        {
            Log.v(TAG, "getQuote() called for " + ticker);
            return 20.0;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "onCreate() called");
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    	    Log.v(TAG, "onDestroy() called");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    	    Log.v(TAG, "onStart() called");
    }

    @Override
    public IBinder onBind(Intent intent)
    {
    	    Log.v(TAG, "onBind() called");
        return new StockQuoteServiceImpl();
    }
}

satya - Saturday, February 27, 2010 8:10:37 PM

Listing 8-13


<service android:name="StockQuoteService">
      <intent-filter>
            <action android:name="com.androidbook.stockquoteservice.IStockQuoteService" />
      </intent-filter>
</service>

satya - Saturday, February 27, 2010 8:11:33 PM

Listing 8-14


// This file is MainActivity.java
import com.androidbook.stockquoteservice.IStockQuoteService;

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.Toast;

public class MainActivity extends Activity {

    protected static final String TAG = "StockQuoteClient";
    private IStockQuoteService stockService = null;

    private Button bindBtn;
    private Button callBtn;
    private Button unbindBtn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                 bindService(new Intent(IStockQuoteService.class
                         .getName()),
                            serConn, Context.BIND_AUTO_CREATE);
                 bindBtn.setEnabled(false);
                 callBtn.setEnabled(true);
                 unbindBtn.setEnabled(true);
            }});

        callBtn = (Button)findViewById(R.id.callBtn);
        callBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                callService();
            }});
        callBtn.setEnabled(false);
        
        unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                unbindService(serConn);
                bindBtn.setEnabled(true);
                callBtn.setEnabled(false);
                unbindBtn.setEnabled(false);
            }});
        unbindBtn.setEnabled(false);
    }

    private void callService() {
        try {
            double val = stockService.getQuote("SYH");
            Toast.makeText(MainActivity.this, "Value from service is "+val, 
Toast.LENGTH_SHORT).show();
        } catch (RemoteException ee) {
            Log.e("MainActivity", ee.getMessage(), ee);
        }
    }

    private ServiceConnection serConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Log.v(TAG, "onServiceConnected() called");
            stockService = IStockQuoteService.Stub.asInterface(service);
            callService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "onServiceDisconnected() called");
        	    stockService = null;
        }
    };
}

satya - Saturday, February 27, 2010 8:12:05 PM

Listing 8-14 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  android:id="@+id/bindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bind"
    />

    <Button android:id="@+id/callBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Call Again"
    />

    <Button android:id="@+id/unbindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UnBind"
    />
</LinearLayout>

satya - Saturday, February 27, 2010 8:12:29 PM

Listing 8-15


// This file is Person.java
package com.syh;
import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
    private int age;
    private String name;
    public static final Parcelable.Creator<Person> CREATOR = 
new Parcelable.Creator<Person>() {
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

    public Person() {
    }

    private Person(Parcel in) {
        readFromParcel(in);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(age);
        out.writeString(name);
    }

    public void readFromParcel(Parcel in) {
        age = in.readInt();
        name = in.readString();
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

satya - Saturday, February 27, 2010 8:12:49 PM

Listing 8-16


package com.syh;
parcelable com.syh.Person

satya - Saturday, February 27, 2010 8:13:16 PM

Listing 8-17


package com.syh;
import com.syh.Person;

interface IStockQuoteService
{
    String getQuote(in String ticker,in Person requester);
}

satya - Saturday, February 27, 2010 8:13:41 PM

Listing 8-18


package com.syh;
// This file is StockQuoteService2.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class StockQuoteService2 extends Service
{
    private NotificationManager notificationMgr;

    public class StockQuoteServiceImpl extends IStockQuoteService.Stub
    {

        @Override
        public String getQuote(String ticker, Person requester)
                throws RemoteException {
            return "Hello "+requester.getName()+"! Quote for "+ticker+" is 20.0";
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();

        notificationMgr =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        displayNotificationMessage("onCreate() called in StockQuoteService2");
    }
    @Override
    public void onDestroy()
    {
        displayNotificationMessage("onDestroy() called in StockQuoteService2");
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        displayNotificationMessage("onBind() called in StockQuoteService2");
        return new StockQuoteServiceImpl();
    }

    private void displayNotificationMessage(String message)
    {
        Notification notification = new Notification(R.drawable.note, 
message,System.currentTimeMillis());

        PendingIntent contentIntent = 
PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        notification.setLatestEventInfo(this, "StockQuoteService2",message, 
contentIntent);

        notificationMgr.notify(R.id.app_notification_id, notification);
    }
}

satya - Saturday, February 27, 2010 8:14:05 PM

Listing 8-18 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<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="This is where the service would ask for help."
    />
</LinearLayout>

satya - Saturday, February 27, 2010 8:14:40 PM

Listing 8-19


<application android:icon="@drawable/icon" android:label="@string/app_name">
	<activity android:name=".MainActivity"
			  android:label="@string/app_name">
		<intent-filter>
			<action android:name="android.intent.action.MAIN" />
		</intent-filter>
	</activity>
<service android:name="StockQuoteService2">
		<intent-filter>
				<action android:name="com.syh.IStockQuoteService" />
		</intent-filter>
</service>
</application>

satya - Saturday, February 27, 2010 8:14:59 PM

Listing 8-20


package com.sayed;
// This file is MainActivity.java

import com.syh.IStockQuoteService;
import com.syh.Person;

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.Toast;

public class MainActivity extends Activity {

    protected static final String TAG = "StockQuoteClient2";
	    private IStockQuoteService stockService = null;
	    
	    private Button bindBtn = null;
	    private Button callBtn = null;
	    private Button unbindBtn = null;

	    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                 bindService(new Intent(IStockQuoteService.class
                         .getName()),
                            serConn, Context.BIND_AUTO_CREATE);
                 bindBtn.setEnabled(false);
                 callBtn.setEnabled(true);
                 unbindBtn.setEnabled(true);
            }});

        callBtn = (Button)findViewById(R.id.callBtn);
        callBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                callService();
            }});
        callBtn.setEnabled(false);
        
        unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                unbindService(serConn);
                bindBtn.setEnabled(true);
                callBtn.setEnabled(false);
                unbindBtn.setEnabled(false);
            }});
        unbindBtn.setEnabled(false);
    }

    private void callService() {
        try {
        	    Person person = new Person();
        	    person.setAge(33);
        	    person.setName("Sayed");
            String response = stockService.getQuote("GOOG", person);
            Toast.makeText(MainActivity.this, "Value from service is "+response, 
Toast.LENGTH_SHORT).show();
        } catch (RemoteException ee) {
            Log.e("MainActivity", ee.getMessage(), ee);
        }
    }

    private ServiceConnection serConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Log.v(TAG, "onServiceConnected() called");
            stockService = IStockQuoteService.Stub.asInterface(service);
            callService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "onServiceDisconnected() called");
        	    stockService = null;
        }
    };
}

satya - Saturday, February 27, 2010 8:15:17 PM

Listing 8-20 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  android:id="@+id/bindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bind"
    />

    <Button android:id="@+id/callBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Call Again"
    />

    <Button android:id="@+id/unbindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UnBind"
    />
</LinearLayout>