您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。