在上面的例子中,能看到从客户端通过binder调用服务端的实现,那么从服务端如何与客户端通信
时间: 2024-03-13 11:45:55 浏览: 25
在 Binder 中,服务端可以通过 IBinder 类中的 transact() 方法向客户端发送消息。下面是一个简单的示例代码,演示了如何在服务端中向客户端发送消息:
1.服务端代码
```java
public class MyService extends Service {
private MyBinder mBinder = new MyBinder();
public class MyBinder extends Binder {
public void sendMessage(String message) {
Parcel data = Parcel.obtain();
data.writeString(message);
// 获取客户端的 IBinder
IBinder clientBinder = getApplicationContext()
.getServiceManager()
.getService("com.example.client");
try {
clientBinder.transact(0, data, null, IBinder.FLAG_ONEWAY);
} catch (RemoteException e) {
e.printStackTrace();
} finally {
data.recycle();
}
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
```
在服务端代码中,我们定义了一个 MyBinder 对象,并实现了 sendMessage() 方法。在 sendMessage() 方法中,我们创建了一个 Parcel 对象,将消息写入 Parcel 中,然后获取客户端的 IBinder 对象,并通过 transact() 方法向客户端发送消息。
2.客户端代码
```java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
```
在客户端代码中,我们定义了一个 BroadcastReceiver 对象,用于接收服务端发送的消息。在 onReceive() 方法中,我们获取到消息,并使用 Toast 将其显示出来。
需要注意的是,服务端在通过 transact() 方法向客户端发送消息时,需要获取客户端的 IBinder 对象。在上面的示例代码中,我们使用了 getApplicationContext().getServiceManager().getService("com.example.client") 来获取客户端的 IBinder 对象,其中 "com.example.client" 是客户端的包名。如果客户端没有在系统服务中注册,服务端将无法获取客户端的 IBinder 对象,从而无法向客户端发送消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)