AIDL传入回调方法
假设现有一个service在接收数据,接收的数据要传给另一个应用的activity使用,可以通过在activity中调用service的aidl的binder接口获取到远程service接口,然后通过该接口提供的设置数据接收回调的方法设置回调对象,从而实现远程service接收数据后,由activity提供的回调对象将数据传递给到activity中(这样做的原因是:aidl是共享内存的,数据共享速度是实时的(wrong),activity传到服务端的listener对象,在到达服务端时,服务端会产生一个新的对象,这2个对象的共同点是:底层Binder是同一个。由于对象是不能跨进程直接传输的,对象的跨进程传输本质都是反序列化的过程)。
//设置回调对象的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的数据共享。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。