2010年4月25日 星期日

如何在Android上發展IPC應用程式



Google Android制訂一套新的語言,稱為AIDL (Android Interface Definition Language)來協助程式設計師發展IPC(InterProcess Communication)應用程式。AIDL是以介面為基礎,類似於COM或Corba但較為輕量,它使用代理類別(Proxy Class)在兩程序(客戶端及實作端)傳遞數值。
本文將介紹如何快速建立AIDL應用程式的步驟:

1. 實作Activity



package com.example.RemoteServiceController;

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RemoteServiceController extends Activity {
private IRemoteService iservice=null;
TextView tv;
private ServiceConnection connection= new ServiceConnection(){


@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iservice = IRemoteService.Stub.asInterface(service);
setTitle("Connect");
int i = 0;
try {
i= iservice.sum(4, 5);

} catch (RemoteException e) {
e.printStackTrace();
}
tv.setText(Integer.toString(i));

}

@Override
public void onServiceDisconnected(ComponentName name) {
iservice = null; }

}; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView) findViewById(R.id.Text01);
Button start = (Button) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
bindService(new Intent(RemoteServiceController.this, RemoteService.class), connection, Context.BIND_AUTO_CREATE);
}

});

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


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(connection);
setTitle("Disonnect");
}

});
}
}

2. 建立AIDL介面



package com.example.RemoteServiceController;

interface IRemoteService {
int sum(int a, int b);
}


3. 建立服務程式




package com.example.RemoteServiceController;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class RemoteService extends Service {
private final IRemoteService.Stub binder= new IRemoteService.Stub(){

@Override
public int sum(int a, int b) throws RemoteException {
return a+b;
}

};
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return this.binder; }
}


4. 修改AndroidManifest.xml
<service android:name="RemoteService" android:process=":remote">
</service>

沒有留言:

張貼留言