Android跨进程监听(ALDL)
背景 : 后台服务处理接收数据,在数据变化时回调给监听的客户端APP
实现方式采用android提供的ALDL
1.后台服务进程(服务器端)
1.新建ALDL文件
package com.test.music;
import com.test.music.IMusicStatusListener;
interface IMusicServiceInterface {
void addMusicStatusListener(IMusicStatusListener listener);
void removeMusicStatusListener(IMusicStatusListener listener);
}
package com.test.music;
interface IMusicStatusListener {
void onModeChange(int mode);
}
aldl文件位置如下图所示 :
2.service中处理逻辑
class ObserveService : Service() {
private val remoteCallbackList =
RemoteCallbackList<IMusicStatusListener>()
override fun onBind(intent: Intent): IBinder? {
return ObserveServiceStub()
}
private fun onMusicModeChanged(mode: Int) {
for (i in 0 until remoteCallbackList.beginBroadcast()) {
try {
remoteCallbackList.getBroadcastItem(i)
.onModeChange(mode)
} catch (e: RemoteException) {
e.printStackTrace()
}
}
remoteCallbackList.finishBroadcast()
}
inner class ObserveServiceStub : IMusicServiceInterface.Stub() {
override fun removeMusicStatusListener(listener: IMusicStatusListener?) {
listener?.let {
remoteCallbackList.unregister(it)
}
}
override fun addMusicStatusListener(listener: IMusicStatusListener?) {
listener?.let {
remoteCallbackList.register(it)
}
}
}
}
2.客户端App(监听服务器端变化)
1.复制服务器端ALDL文件到相同位置
2. 客户端连接服务
private IMusicServiceInterface iMusicServiceInterface;
private InternalMusicStatusListener internalMusicStatusListener;
private ServiceConnection serviceConnection;
Intent serviceIntent = new Intent();
serviceIntent.setPackage(MUSIC_PACKAGE);
serviceIntent.setAction(MUSIC_ACTION);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMusicServiceInterface = IMusicServiceInterface.Stub.asInterface(service);
try {
iMusicServiceInterface.addMusicStatusListener(internalMusicStatusListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
getContext().bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
internalMusicStatusListener = new InternalMusicStatusListener();
private class InternalMusicStatusListener extends IMusicStatusListener.Stub {
@Override
public void onModeChange(int mode) throws RemoteException {
updateMusicModeIcon(mode);
}
}
有问题欢迎在评论区留言讨论
|