When you are a Android Application Designer, you must know how to use AIDL.

AIDL (Android Interface Definition Language) is IPC mechanism in Android Environment.

What is IPC? The full name of IPC is Inter-process communication.

If there are two processes, they want to communicate with each other.

You could implement IPC by using the mechanism - AIDL.

Suppose you don't have any idea how to start using IPC.

This example is from http://mylifewithandroid.blogspot.com/2008/01/about-binders.html

You can download code and refer it.

More information you can get from Android Official Webiste

More Examples, you can see http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/index.html

 


 

[Step 1. Create Your Filename.aidl]

[IAsyncService.aidl]

package org.devtcg.asyncservice;

import org.devtcg.asyncservice.IAsyncServiceCounter;

interface IAsyncService
{
    /* Start the asynchronous counting sequence.  The service will count to `to', pausing
     * 1 second between each interval. */

    void startCount(int to, IAsyncServiceCounter callback);
}

 

[IAsyncServiceCounter.aidl]

package org.devtcg.asyncservice;

interface IAsyncServiceCounter

{

    void handleCount(int n);
}

 


 

[Step 2. Implement Your Service - AsyncService.java]

package org.devtcg.asyncservice;

import android.app.Service;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.util.Log;

public class AsyncService extends Service
{
    private static final String TAG = "AsyncService";
   
    @Override
    protected void onCreate()
    {
        Log.d(TAG, "onCreate");
    }
   
    @Override
    protected void onDestroy()
    {
        /* TODO: Of course we would need to clean up. */
        Log.d(TAG, "onDestroy");
    }
   
    @Override
    public IBinder getBinder()
    {
        return mBinder;
    }

    //implement Binder
    private final IAsyncService.Stub mBinder = new IAsyncService.Stub()
    {
        public void startCount(final int to, final IAsyncServiceCounter callback)
        {
            Thread t = new Thread()
            {
                /* Survives interruption, but not otherwise more precise. */
                public void preciseSleep(long millis)
                {
                    long endTime = System.currentTimeMillis() + millis;

                    do {
                        try
                        {
                            Thread.sleep(endTime - System.currentTimeMillis());
                        }
                        catch (InterruptedException e)
                        {}
                    } while (System.currentTimeMillis() < endTime);
                }

                public void run()
                {
                    for (int i = 1; i <= to; i++)
                    {
                        preciseSleep(1000);

                        try
                        {
                            callback.handleCount(i);
                        }
                        catch (DeadObjectException e)
                        {
                            Log.d(TAG, "Dead peer, aborting...", e);
                            break;
                        }
                    }
                }
            };

            t.start();
        }
    };

}


 


 

[Step 3. Coding Your Client - AsyncClient.java]

package org.devtcg.asyncservice;

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.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AsyncClient extends Activity
{
    private static final String TAG = "AsyncClient";
   
    private Handler mHandler = new Handler();

    //Declare Your AIDL Object
    private IAsyncService mService;

    private TextView mCounterText;

    private boolean mCounting = false;
   
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main);
       
        mCounterText = (TextView)findViewById(R.id.counter);
       
        Button b = (Button)findViewById(R.id.start);
        b.setOnClickListener(mFire);
        //Binding the Service
        bindService(new Intent(this, AsyncService.class), null, mConnection,
          Context.BIND_AUTO_CREATE);

    }
   
    protected OnClickListener mFire = new OnClickListener()
    {
        public void onClick(View view)
        {
            if (mService == null)
            {
                Log.d(TAG, "Nothing to do!");
                return;
            }

            if (mCounting == true)
            {
                /* This would be simple to work around, if you're curious. */
                Log.d(TAG, "mCounter is implemented globally and cannot be reused while counting is in progress.");
                return;
            }

            try
            {
                mCounting = true;
                mService.startCount(10, mCounter);
                Log.d(TAG, "Counting has begun...");
            }
            catch (DeadObjectException e)
            {
                mCounting = false;
                Log.d(TAG, Log.getStackTraceString(e));
            }
        }
    };
    //Create a Service connection
    private ServiceConnection mConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            Log.d(TAG, "onServiceConnected");
            mService = IAsyncService.Stub.asInterface((IBinder)service);
        }
       
        public void onServiceDisconnected(ComponentName className)
        {
            Log.d(TAG, "onServiceDisconnected");
            mService = null;
        }
    };

   

    //Your call AIDL callback interface
    private IAsyncServiceCounter.Stub mCounter = new IAsyncServiceCounter.Stub()
    {
        public void handleCount(final int n)
        {
            Log.d(TAG, "handleCount(" + n + ")");

            mHandler.post(new Runnable()
            {
                public void run()
                {
                    if (n == 10)
                    {
                        mCounterText.setText("Done!");
                        mCounting = false;
                    }
                    else
                        mCounterText.setText(String.valueOf(n));
                }
            });
        }
    };

}


It is an easy example to implement AIDL.

Just Enjoy it. Chow it...........

arrow
arrow
    全站熱搜

    owenhuangtw 發表在 痞客邦 留言(0) 人氣()