1. 程式人生 > >【Android開發】Android跨程序通訊(AIDL)官方文件及官方Demo講解

【Android開發】Android跨程序通訊(AIDL)官方文件及官方Demo講解

第一章、 關於Android跨程序的思考

先來回顧一下作業系統中的一些概念。
 同一個程序中可以有多個執行緒,執行緒間通訊可以直接取得地址。因為Java程式的記憶體分配在連續的地址空間。
 預設一個Java程式會開啟一個程序,執行在JVM中。但是一個JVM是可以開啟多個程序的。
 一個或多個作業系統可以開啟多個JVM,多個JVM之間依賴TCP通訊的方法呼叫即Java的RMI(Remote Method Interface)機制,即分散式計算的模型。
具體到Android的應用場景:假如一個app中有個Service用於TCP通訊,不斷接受資料和影象等,則可以將該Service設定為新的程序,這樣,即便程式出現Bug死掉,後臺服務仍然在執行,當程式重啟時,可以繼續接受資料和影象。
另外一個應用場景:將用於TCP通訊的Service獨立開發成一個app,其它多個app可以通過跨程序連線到該Service,並接受資料。包含Servie的這個app就可以管理多個與之相連的app。
注意,Android不允許沒有UI即沒有Activity的Service出現。所以,如果Service與Activity之間需要解耦,則可以將Service放到新的執行緒中。Android中跨程序機制有Messenger和AIDL,應用場景如下:
 如果Servie和Activity在同一APK中,可以使用Messenger和AIDL,如圖1;
 如果Servie和Activity在不同APK,只能使用AIDL,如圖2;
當然,廣播也是一種方式,但是廣播是作業系統級的,資源消耗大,對於大量且頻繁的資料通訊,並不推薦使用。
這裡寫圖片描述


圖1,跨程序模式,1個app中將Service放到新的程序中
這裡寫圖片描述
圖2,跨程序模式,多個app連線遠端服務(沒有必要Service和Activy再放在不同的程序中,當然,也可以)。

這裡的第二章到第五章來自於Android官方Training,如果無法訪問,可以這裡看;否則直接跳到第六章。

第二章、 前言

AIDL (Android Interface Definition Language) is similar to other IDLs you might have worked with. It allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC). On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose(分解) their objects into primitives that the operating system can understand, and marshall the objects across that boundary for you. The code to do that marshalling is tedious(單調沉悶的) to write, so Android handles it for you with AIDL.
Note: 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. Regardless, be sure that you understand Bound Services before implementing an AIDL.
Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are direct function calls. You should not make assumptions about the thread in which the call occurs.(方法中不能出現執行緒) What happens is different depending on whether the call is from a thread in the local process or a remote process. Specifically:
• Calls made from the local process are executed in the same thread that is making the call. If this is your main UI thread, that thread continues to execute in the AIDL interface. If it is another thread, that is the one that executes your code in the service. Thus, if only local threads are accessing the service, you can completely control which threads are executing in it (but if that is the case, then you shouldn’t be using AIDL at all, but should instead create the interface by implementing a Binder).方法請求和方法執行是在同一個執行緒中。
• Calls from a remote process are dispatched from a thread pool the platform maintains inside of your own process. You must be prepared for incoming calls from unknown threads, with multiple calls happening at the same time. In other words, an implementation of an AIDL interface must be completely thread-safe.請求的方法被分派到不同的執行緒,所以這些AIDL介面必須是執行緒安全的。
• The oneway keyword modifies the behavior of remote calls. When used, a remote call does not block; it simply sends the transaction data and immediately returns. The implementation of the interface eventually receives this as a regular call from the Binder thread pool as a normal remote call. If oneway is used with a local call, there is no impact and the call is still synchronous.使用oneway關鍵字修飾方法,該方法不能阻塞。假如用於本地呼叫,該關鍵詞沒有效力,該方法仍然能使用同步。

第三章、 Defining an AIDL Interface

You must define your AIDL interface in an .aidl file using the Java programming language syntax, then save it in the source code (in the src/ directory) of both the application hosting the service and any other application that binds to the service.
When you build each application that contains the .aidl file, the Android SDK tools generate an IBinder interface based on the .aidl file and save it in the project’s gen/ directory. The service must implement the IBinder interface as appropriate. The client applications can then bind to the service and call methods from the IBinder to perform IPC.
To create a bounded service using AIDL, follow these steps:
1. Create the .aidl file
This file defines the programming interface with method signatures.
2. Implement the interface
The Android SDK tools generate an interface in the Java programming language, based on your .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from your AIDL interface. You must extend the Stub class and implement the methods.
3. Expose the interface to clients
Implement a Service and override onBind() to return your implementation of the Stub class.
Caution: Any changes that you make to your AIDL interface after your first release must remain backward compatible in order to avoid breaking other applications that use your service. That is, because your .aidl file must be copied to other applications in order for them to access your service’s interface, you must maintain support for the original interface.
1. Create the .aidl file
AIDL uses a simple syntax that lets you declare an interface with one or more methods that can take parameters and return values. The parameters and return values can be of any type, even other AIDL-generated interfaces.
You must construct the .aidl file using the Java programming language. Each .aidl file must define a single interface and requires only the interface declaration and method signatures.
By default, AIDL supports the following data types:
• All primitive types in the Java programming language (such as int, long, char, boolean, and so on)
• String
• CharSequence
• List
All elements in the List must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you’ve declared. A List may optionally be used as a “generic” class (for example, List). The actual concrete class that the other side receives is always an ArrayList, although the method is generated to use the List interface.
• Map
All elements in the Map must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you’ve declared. Generic maps, (such as those of the form Map

// IRemoteService.aidl
package com.example.android;

// 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);
}

Simply save your .aidl file in your project’s src/ directory and when you build your application, the SDK tools generate the IBinder interface file in your project’s gen/ directory. The generated file name matches the .aidl file name, but with a .java extension (for example, IRemoteService.aidl results in IRemoteService.java).
If you use Eclipse, the incremental build generates the binder class almost immediately. If you do not use Eclipse, then the Ant tool generates the binder class next time you build your application—you should build your project with ant debug (or ant release) as soon as you’re finished writing the .aidl file, so that your code can link against the generated class.
2. Implement the interface
When you build your application, the Android SDK tools generate a .java interface file named after your .aidl file. The generated interface includes a subclass named Stub that is an abstract implementation of its parent interface (for example, YourInterface.Stub) and declares all the methods from the .aidl file.
Note: Stub also defines a few helper methods, most notably asInterface(), which takes an IBinder (usually the one passed to a client’s onServiceConnected() callback method) and returns an instance of the stub interface. See the section Calling an IPC Method for more details on how to make this cast.
To implement the interface generated from the .aidl, extend the generated Binder interface (for example, YourInterface.Stub) and implement the methods inherited from the .aidl file.
Here is an example implementation of an interface called IRemoteService (defined by the IRemoteService.aidl example, above) using an anonymous instance:

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    public int getPid(){
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
        float aFloat, double aDouble, String aString) {
        // Does nothing
    }
};

Now the mBinder is an instance of the Stub class (a Binder), which defines the RPC interface for the service. In the next step, this instance is exposed to clients so they can interact with the service.
There are a few rules you should be aware of when implementing your AIDL interface:
• Incoming calls are not guaranteed to be executed on the main thread, so you need to think about multithreading from the start and properly build your service to be thread-safe.入境請求不能保證在主執行緒中執行,所以,你一開始就該考慮多執行緒,並使得你的service是執行緒安全的。
• By default, RPC calls are synchronous. If you know that the service takes more than a few milliseconds to complete a request, you should not call it from the activity’s main thread, because it might hang the application (Android might display an “Application is Not Responding” dialog)—you should usually call them from a separate thread in the client.
• No exceptions that you throw are sent back to the caller.不能給caller丟擲異常
3. Expose the interface to clients
Once you’ve implemented the interface for your service, you need to expose it to clients so they can bind to it. To expose the interface for your service, extend Service and implement onBind() to return an instance of your class that implements the generated Stub (as discussed in the previous section). Here’s an example service that exposes the IRemoteService example interface to clients.

public class RemoteService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the interface
        return mBinder;
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid(){
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
            // Does nothing
        }
    };
}

Now, when a client (such as an activity) calls bindService() to connect to this service, the client’s onServiceConnected() callback receives the mBinder instance returned by the service’s onBind() method.
The client must also have access to the interface class, so if the client and service are in separate applications, then the client’s application must have a copy of the .aidl file in its src/ directory (which generates the android.os.Binder interface—providing the client access to the AIDL methods).
When the client receives the IBinder in the onServiceConnected() callback, it must call YourServiceInterface.Stub.asInterface(service) to cast the returned parameter to YourServiceInterface type. For example:

IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the example above for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service
        mIRemoteService = IRemoteService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        mIRemoteService = null;
    }
};

For more sample code, see the RemoteService.java class in ApiDemos.

第四章、 Passing Objects over IPC

If you have a class that you would like to send from one process to another through an IPC interface, you can do that. However, you must ensure that the code for your class is available to the other side of the IPC channel and your class must support the Parcelable interface. Supporting the Parcelable interface is important because it allows the Android system to decompose objects into primitives that can be marshalled across processes.
To create a class that supports the Parcelable protocol, you must do the following:
1. Make your class implement the Parcelable interface.
2. Implement writeToParcel, which takes the current state of the object and writes it to a Parcel.
3. Add a static field called CREATOR to your class which is an object implementing the Parcelable.Creator interface.
4. Finally, create an .aidl file that declares your parcelable class (as shown for the Rect.aidl file, below). If you are using a custom build process, do not add the .aidl file to your build. Similar to a header file in the C language, this .aidl file isn’t compiled.
AIDL uses these methods and fields in the code it generates to marshall and unmarshall your objects.
For example, here is a Rect.aidl file to create a Rect class that’s parcelable:
package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;

And here is an example of how the Rect class implements the Parcelable protocol.

import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }

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

    public Rect() {
    }

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

    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

The marshalling in the Rect class is pretty simple. Take a look at the other methods on Parcel to see the other kinds of values you can write to a Parcel.
Warning: Don’t forget the security implications of receiving data from other processes. In this case, the Rect reads four numbers from the Parcel, but it is up to you to ensure that these are within the acceptable range of values for whatever the caller is trying to do. See Security and Permissions for more information about how to keep your application secure from malware.

第五章、 Calling an IPC Method

Here are the steps a calling class must take to call a remote interface defined with AIDL:
1. Include the .aidl file in the project src/ directory.
2. Declare an instance of the IBinder interface (generated based on the AIDL).
3. Implement ServiceConnection.
4. Call Context.bindService(), passing in your ServiceConnection implementation.
5. In your implementation of onServiceConnected(), you will receive an IBinder instance (called service). Call YourInterfaceName.Stub.asInterface((IBinder)service) to cast the returned parameter to YourInterface type.
6. Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are thrown when the connection has broken; this will be the only exception thrown by remote methods.
7. To disconnect, call Context.unbindService() with the instance of your interface.
A few comments on calling an IPC service:
• Objects are reference counted across processes.
• You can send anonymous objects as method arguments.
For more information about binding to a service, read the Bound Services document.
Here is some sample code demonstrating calling an AIDL-created service, taken from the Remote Service sample in the ApiDemos project.

public static class Binding extends Activity {
    /** The primary interface we will be calling on the service. */
    IRemoteService mService = null;
    /** Another interface we use on the service. */
    ISecondary mSecondaryService = null;

    Button mKillButton;
    TextView mCallbackText;

    private boolean mIsBound;

    /**
     * Standard initialization of this activity.  Set up the UI, then wait
     * for the user to poke it before doing anything.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.remote_service_binding);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
        mKillButton = (Button)findViewById(R.id.kill);
        mKillButton.setOnClickListener(mKillListener);
        mKillButton.setEnabled(false);

        mCallbackText = (TextView)findViewById(R.id.callback);
        mCallbackText.setText("Not attached.");
    }

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service);
            mKillButton.setEnabled(true);
            mCallbackText.setText("Attached.");

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even
                // do anything with it; we can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mKillButton.setEnabled(false);
            mCallbackText.setText("Disconnected.");

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Class for interacting with the secondary interface of the service.
     */
    private ServiceConnection mSecondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            mSecondaryService = ISecondary.Stub.asInterface(service);
            mKillButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            mSecondaryService = null;
            mKillButton.setEnabled(false);
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            // Establish a couple connections with the service, binding
            // by interface names.  This allows other applications to be
            // installed that replace the remote service by implementing
            // the same interface.
            Intent intent = new Intent(Binding.this, RemoteService.class);
            intent.setAction(IRemoteService.class.getName());
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            intent.setAction(ISecondary.class.getName());
            bindService(intent, mSecondaryConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mCallbackText.setText("Binding.");
        }
    };

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                // If we have received the service, and hence registered with
                // it, then now is the time to unregister.
                if (mService != null) {
                    try {
                        mService.unregisterCallback(mCallback);
                    } catch (RemoteException e) {
                        // There is nothing special we need to do if the service
                        // has crashed.
                    }
                }

                // Detach our existing connection.
                unbindService(mConnection);
                unbindService(mSecondaryConnection);
                mKillButton.setEnabled(false);
                mIsBound = false;
                mCallbackText.setText("Unbinding.");
            }
        }
    };

    private OnClickListener mKillListener = new OnClickListener() {
        public void onClick(View v) {
            // To kill the process hosting our service, we need to know its
            // PID.  Conveniently our service has a call that will return
            // to us that information.
            if (mSecondaryService != null) {
                try {
                    int pid = mSecondaryService.getPid();
                    // Note that, though this API allows us to request to
                    // kill any process based on its PID, the kernel will
                    // still impose standard restrictions on which PIDs you
                    // are actually able to kill.  Typically this means only
                    // the process running your application and any additional
                    // processes created by that app as shown here; packages
                    // sharing a common UID will also be able to kill each
                    // other's processes.
                    Process.killProcess(pid);
                    mCallbackText.setText("Killed service process.");
                } catch (RemoteException ex) {
                    // Recover gracefully from the process hosting the
                    // server dying.
                    // Just for purposes of the sample, put up a notification.
                    Toast.makeText(Binding.this,
                            R.string.remote_call_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    // ----------------------------------------------------------------------
    // Code showing how to deal with callbacks.
    // ----------------------------------------------------------------------

    /**
     * This implementation is used to receive callbacks from the remote
     * service.
     */
    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here will
         * NOT be running in our main thread like most other things -- so,
         * to update the UI, we need to use a Handler to hop over there.
         */
        public void valueChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
        }
    };

    private static final int BUMP_MSG = 1;

    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case BUMP_MSG:
                    mCallbackText.setText("Received from service: " + msg.arg1);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }

    };
}

第六章、 官方Demo –RemoteService

官方講解中的例子都來自於官方Demo的一個例項。官方Demo Activity和Service是在同一個apk中,在SDK中位置是sdk\samples\android-15\ApiDemos\src\com\example\android\apis\app,檔案是RemoteServic.java以及3個AIDL介面檔案。
效果是Activity中繫結後臺服務,並將AIDL回撥物件傳遞給後臺服務,後臺服務是在新的程序中,不斷遞增一個int型別的數,並呼叫傳遞進來的AIDL物件中的方法,即顯示在了Activity中了。可以開啟模擬器(api=15)檢視該Demo的執行效果。
1. AIDL設定
共有3個AIDL介面。IremoteService的引數也是AIDL介面

/**
 * Example of defining an interface for calling on to a remote service
 * (running in another process).
 */
interface IRemoteService {
    /**
     * Often you want to allow a service to call back to its clients.
     * This shows how to do so, by registering a callback interface with
     * the service.
     */
    void registerCallback(IRemoteServiceCallback cb);

    /**
     * Remove a previously registered callback interface.
     */
    void unregisterCallback(IRemoteServiceCallback cb);
}

在Client中實現該介面,並作為IremoteService介面中方法的引數。注意,這裡的引數可以是實現了Parcelable介面的複雜物件。

/**
* Example of a callback interface used by IRemoteService to send
* synchronous notifications back to its clients. Note that this is a
* one-way interface so the server does not block waiting for the client.
*/
oneway interface IRemoteServiceCallback {
/**
* Called when the service has a new value for you.
*/
void valueChanged(int value);
}

```

*************************************************************************
可以通過AIDL獲得遠端服務的程序號,進而可以kill該程序。

interface ISecondary {
/**
* Request the PID of this service, to do evil things with it.
*/
int getPid();

/**
 * This demonstrates the 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);

}


2.  遠端服務
第1步:分別實現IRemoteService和ISecondary

/**
* The IRemoteInterface is defined through IDL
*/
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public void registerCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.register(cb);//將Client中實現的AIDL介面加入到Service的連結串列中
}
public void unregisterCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.unregister(cb);
}
};

/**
 * A secondary interface to the service.
 */
private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
    public int getPid() {
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
    }

};


*************************************************************************
這裡要注意,Client端實現的IRemoteServiceCallback介面被新增到了連結串列中:
    private final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>();
*************************************************************************


第2步:設定服務被連線時的返回型別

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
// Select the interface to return. If your service only implements
// a single interface, you can just return it here without checking
// the Intent.
if (IRemoteService.class.getName().equals(intent.getAction())) {
return mBinder;
}
if (ISecondary.class.getName().equals(intent.getAction())) {
return mSecondaryBinder;
}
return null;
}


第3步:服務中資料的模擬,這裡是不斷累加一個數,然後通知Client

/**
* Our Handler used to execute operations on the main thread. This is used
* to schedule increments of our value.
*/
private final Handler mHandler = new Handler() {
@SuppressLint(“HandlerLeak”)
@Override public void handleMessage(Message msg) {
switch (msg.what) {

            // It is time to bump the value!
            case REPORT_MSG: {
                // Up it goes.
                int value = ++mValue;

                // Broadcast to all clients the new value.
                final int N = mCallbacks.beginBroadcast();
                for (int i=0; i<N; i++) {
                    try {
                        mCallbacks.getBroadcastItem(i).valueChanged(value);//回撥所有需要通知的Client介面
                    } catch (RemoteException e) {
                        // The RemoteCallbackList will take care of removing
                        // the dead object for us.
                    }
                }
                mCallbacks.finishBroadcast();

                // Repeat every 1 second.
                sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
            } break;
            default:
                super.handleMessage(msg);
        }
    }

};


*************************************************************************
注意,這裡一旦更改了值,就通知所有的Client,即呼叫IRemoteServiceCallback中的方法,這樣,Client中就收到了通知。

第4步:其他,在Manifest中修改Service的屬性,新增:remote,並加入3個Action。Action值最好採用對應的AIDL全名稱。

*************************************************************************
3.  Client端
  Client端最好先通過Start的方式啟動Service,再通過Bind的方式繫結該服務。這樣,一旦Client掛掉,Service仍然在執行。否則,僅僅通過Bind的方式啟動並繫結服務,一旦Client掛掉,Service也會一起死掉(儘管是不同程序)。
第1步,初始化連線類

/* The primary interface we will be calling on the service. /
IRemoteService mService = null;
/* Another interface we use on the service. /
ISecondary mSecondaryService = null;

/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = IRemoteService.Stub.asInterface(service);
mKillButton.setEnabled(true);
mCallbackText.setText(“Attached.”);

        // We want to monitor the service for as long as we are
        // connected to it.
        try {
            mService.registerCallback(mCallback);
        } catch (RemoteException e) {
            // In this case the service has crashed before we could even
            // do anything with it; we can count on soon being
            // disconnected (and then reconnected if it can be restarted)
            // so there is no need to do anything here.
        }

        // As part of the sample, tell the user what happened.
        Toast.makeText(BindingActivity.this,
                R.string.remote_service_connected, Toast.LENGTH_SHORT)
                .show();
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mService = null;
        mKillButton.setEnabled(false);
        mCallbackText.setText("Disconnected.");

        // As part of the sample, tell the user what happened.
        Toast.makeText(BindingActivity.this,
                R.string.remote_service_disconnected, Toast.LENGTH_SHORT)
                .show();
    }
};
/**
 * Class for interacting with the secondary interface of the service.
 */
private ServiceConnection mSecondaryConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Connecting to a secondary interface is the same as any
        // other interface.
        mSecondaryService = ISecondary.Stub.asInterface(service);
        mKillButton.setEnabled(true);
    }

    public void onServiceDisconnected(ComponentName className) {
        mSecondaryService = null;
        mKillButton.setEnabled(false);
    }
};

第2步:Start方式啟動Service
@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    startService(new Intent(BindingActivity.this, RemoteService.class));
}

第3步:Bind方式繫結Service
bindService(new Intent(IRemoteService.class.getName()),
                mConnection, Context.BIND_AUTO_CREATE);
        bindService(new Intent(ISecondary.class.getName()),
                mSecondaryConnection, Context.BIND_AUTO_CREATE);
4步:實現IRemoteServiceCallback
/**
 * This implementation is used to receive callbacks from the remote service.
 */
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
    /**
     * This is called by the remote service regularly to tell us about new
     * values. Note that IPC calls are dispatched through a thread pool
     * running in each process, so the code executing here will NOT be
     * running in our main thread like most other things -- so, to update
     * the UI, we need to use a Handler to hop over there.
     */
    public void valueChanged(int value) {
        mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
    }
};

4.  完整程式碼

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.apis.app;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

/**
* This is an example of implementing an application service that runs in a
* different process than the application. Because it can be in another
* process, we must use IPC to interact with it. The
* {@link Controller} and {@link Binding} classes
* show how to interact with the service.
*
*

Note that most applications do not need to deal with
* the complexity shown here. If your application simply has a service
* running in its own process, the {@link LocalService} sample shows a much
* simpler way to interact with it.
*/
public class RemoteService extends Service {
/**
* This is a list of callbacks that have been registered with the
* service. Note that this is package scoped (instead of private) so
* that it can be accessed more efficiently from inner classes.
*/
final RemoteCallbackList mCallbacks
= new RemoteCallbackList();

int mValue = 0;
NotificationManager mNM;

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Display a notification about us starting.
    showNotification();

    // While this service is running, it will continually increment a
    // number.  Send the first message that is used to perform the
    // increment.
    mHandler.sendEmptyMessage(REPORT_MSG);
}

@Override
public void onDestroy() {
    // Cancel the persistent notification.
    mNM.cancel(R.string.remote_service_started);

    // Tell the user we stopped.
    Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();

    // Unregister all callbacks.
    mCallbacks.kill();

    // Remove the next pending message to increment the counter, stopping
    // the increment loop.
    mHandler.removeMessages(REPORT_MSG);
}


@Override
public IBinder onBind(Intent intent) {
    // Select the interface to return.  If your service only implements
    // a single interface, you can just return it here without checking
    // the Intent.
    if (IRemoteService.class.getName().equals(intent.getAction())) {
        return mBinder;
    }
    if (ISecondary.class.getName().equals(intent.getAction())) {
        return mSecondaryBinder;
    }
    return null;
}

/**
 * The IRemoteInterface is defined through IDL
 */
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    public void registerCallback(IRemoteServiceCallback cb) {
        if (cb != null) mCallbacks.register(cb);
    }
    public void unregisterCallback(IRemoteServiceCallback cb) {
        if (cb != null) mCallbacks.unregister(cb);
    }
};

/**
 * A secondary interface to the service.
 */
private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
    public int getPid() {
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
    }
};


@Override
public void onTaskRemoved(Intent rootIntent) {
    Toast.makeText(this, "Task removed: " + rootIntent, Toast.LENGTH_LONG).show();
}

private static final int REPORT_MSG = 1;

/**
 * Our Handler used to execute operations on the main thread.  This is used
 * to schedule increments of our value.
 */
private final Handler mHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
        switch (msg.what) {

            // It is time to bump the value!
            case REPORT_MSG: {
                // Up it goes.
                int value = ++mValue;

                // Broadcast to all clients the new value.
                final int N = mCallbacks.beginBroadcast();
                for (int i=0; i<N; i++) {
                    try {
                        mCallbacks.getBroadcastItem(i).valueChanged(value);
                    } catch (RemoteException e) {
                        // The RemoteCallbackList will take care of removing
                        // the dead object for us.
                    }
                }
                mCallbacks.finishBroadcast();

                // Repeat every 1 second.
                sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
            } break;
            default:
                super.handleMessage(msg);
        }
    }
};

/**
 * Show a notification while this service is running.
 */
private void showNotification() {
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.remote_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.stat_sample, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, Controller.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                   text, contentIntent);

    // Send the notification.
    // We use a string id because it is a unique number.  We use it later to cancel.
    mNM.notify(R.string.remote_service_started, notification);
}

// ----------------------------------------------------------------------

/**
 * <p>Example of explicitly starting and stopping the remove service.
 * This demonstrates the implementation of a service that runs in a different
 * process than the rest of the application, which is explicitly started and stopped
 * as desired.</p>
 * 
 * <p>Note that this is implemented as an inner class only keep the sample
 * all together; typically this code would appear in some separate class.
 */
public static class Controller extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.remote_service_controller);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.start);
        button.setOnClickListener(mStartListener);
        button = (Button)findViewById(R.id.stop);
        button.setOnClickListener(mStopListener);
    }

    private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            // Make sure the service is started.  It will continue running
            // until someone calls stopService().
            // We use an action code here, instead of explictly supplying
            // the component name, so that other packages can replace
            // the service.
            startService(new Intent(
                    "com.example.android.apis.app.REMOTE_SERVICE"));
        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            // Cancel a previous call to startService().  Note that the
            // service will not actually stop at this point if there are
            // still bound clients.
            stopService(new Intent(
                    "com.example.android.apis.app.REMOTE_SERVICE"));
        }
    };
}

// ----------------------------------------------------------------------

/**
 * Example of binding and unbinding to the remote service.
 * This demonstrates the implementation of a service which the client will
 * bind to, interacting with it through an aidl interface.</p>
 * 
 * <p>Note that this is implemented as an inner class only keep the sample
 * all together; typically this code would appear in some separate class.
 */

public static class Binding extends Activity {
    /** The primary interface we will be calling on the service. */
    IRemoteService mService = null;
    /** Another interface we use on the service. */
    ISecondary mSecondaryService = null;

    Button mKillButton;
    TextView mCallbackText;

    private boolean mIsBound;

    /**
     * Standard initialization of this activity.  Set up the UI, then wait
     * for the user to poke it before doing anything.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.remote_service_binding);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
        mKillButton = (Button)findViewById(R.id.kill);
        mKillButton.setOnClickListener(mKillListener);
        mKillButton.setEnabled(false);

        mCallbackText = (TextView)findViewById(R.id.callback);
        mCallbackText.setText("Not attached.");
    }

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service);
            mKillButton.setEnabled(true);
            mCallbackText.setText("Attached.");

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even
                // do anything with it; we can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mKillButton.setEnabled(false);
            mCallbackText.setText("Disconnected.");

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Class for interacting with the secondary interface of the service.
     */
    private ServiceConnection mSecondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            mSecondaryService = ISecondary.Stub.asInterface(service);
            mKillButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            mSecondaryService = null;
            mKillButton.setEnabled(false);
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            // Esta