在Android應用程序開發中,可能會遇到跨進程回調問題,比如,調用一個服務,但服務是異步的,服務完成後,需要給客戶一個通知,這時就需要用到跨進程回調了。跨進程回調本質上用到了Binder機制,其過程如下:
1.定義aidl
ITest.aidl
package com.example.chirpdemo;
import com.example.chirpdemo.ITestListener;
interface ITest {
int getValue();
void setValue(int value);
void listen(ITestListener listener);
}
ITestListener.aidl
package com.example.chirpdemo;
interface ITestListener {
void onFinished(int result);
}
2.Service定義如下:
package com.example.chirpdemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
final private static String TAG = "MyService";
public class ServiceImpl extends ITest.Stub {
private int mValue;
private ITestListener mListener;
public ServiceImpl() {
mValue = 0;
}
@Override
public int getValue() throws RemoteException {
return mValue;
}
@Override
public void setValue(int value) throws RemoteException {
mValue = value;
if (null != mListener) {
mListener.onFinished(-1);
}
}
@Override
public void listen(ITestListener listener) throws RemoteException {
mListener = listener;
}
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "onStart");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind");
super.onRebind(intent);
}
@Override
public IBinder onBind(Intent arg0) {
return new ServiceImpl();
}
}