AIDL传入回调方法
假设现有一个service在接收数据,接收的数据要传给另一个应用的activity使用,可以通过在activity中调用service的aidl的binder接口获取到远程service接口,然后通过该接口提供的设置数据接收回调的方法设置回调对象,从而实现远程service接收数据后,由activity提供的回调对象将数据传递给到activity中(这样做的原因是:aidl是共享内存的,数据共享速度是实时的)。
//设置回调对象的aidl
package com.test.aidl;
import com.test.aidl.InterProcessCallback;
interface IAIDLSetCallback
{
void setCallback(InterProcessCallback callback);
}
//回调接口aidl,因为InterProcessCallback在activity和service中都要使用,所以必须定义出aidl
package com.test.aidl;
interface InterProcessCallback
{
void recv(int val);
}
//service
public class AIDLService extends Service {
//回调对象实例
private InterProcessCallback callback;
//模拟service接收数据
private Random random;
@Override
public void onCreate() {
super.onCreate();
random = new Random(System.currentTimeMillis());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//如果activity已经传入回调对象,则获取数据传给activity.
if(callback != null)
{
try {
callback.testCallback(random.nextInt());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
},0,10);
}
private IAIDLSetCallback.Stub binder = new IAIDLSetCallback.Stub()
{
@Override
public void setCallback(InterProcessCallback callback)
throws RemoteException {
AIDLService.this.callback = callback;
}
};
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
//activity
public class MainActivity extends Activity {
private TextView tvRecvValue;
private IAIDLSetCallback aidlService;
private InterProcessCallback interProcessCallback = new InterProcessCallback.Stub() {
@Override
public void recv(int val) throws RemoteException {
final int nVal = val;
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tvRecvValue.setText(nVal+"");
}
});
}
};
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
aidlService = AidlGetServiceData.Stub.asInterface(service);
try {
//设置回调对象
aidlService.setCallback(interProcessCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name)
{
aidlService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvRecvValue = (TextView)findViewById(R.id.tvRecvValue);
Intent intent = new Intent("com.example.aidl.action.AIDL_TEST");
intent.setPackage("com.example.aidl_service");
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unbindService(conn);
}
}
通过以上操作,就可以实现在service中接收数据,然后通过回调对象InterProcessCallback将数据回调给activity,从而完成远程service和activity的数据共享。
本文出自 “whatever957” 博客,请务必保留此出处http://whatever957.blog.51cto.com/6835003/1827431
原文地址:http://whatever957.blog.51cto.com/6835003/1827431