这个demo演示了如何与远程服务(当前的activity与服务不在同一进程当中)进行通讯
* 演示了如何利用RemoteCallbackList实现服务端回调客户端的功能
创建一个工程,作为服务端
ProcessId.aidl文件
package com.fishtosky.remoteservice;
interface ProcessId{
void killProcess();
}
IRemoteService.aidl
package com.fishtosky.remoteservice;
import com.fishtosky.remoteservice.IRemoteServiceCallBack;
interface IRemoteService{
void registerCallback(IRemoteServiceCallBack cb);
void unRegisterCallback(IRemoteServiceCallBack cb);
}
IRmoteServiceCallBack.aidl
package com.fishtosky.remoteservice;
interface IRemoteServiceCallBack{
void valueChange(int value);
}
RemoteService.java
public class RemoteService extends Service {
/*
* 对于这个类的理解可能参考Messenger那个demo中我们讲到的双向通讯中,定义的那个用于存放 客户端信使的那个List集合。
* 其实这个远程回调集合就是用来存放在客户端中实现的回调接口的一个集合
* IRemoteServiceCallBack这个接口在客户端实现,在服务端调用。实现的是服务端回调 客户端的功能
* 因为一个服务端可以对应多个客户端,所以要用一个集合来存放
*/
private RemoteCallbackList<IRemoteServiceCallBack> mCallbacks = new RemoteCallbackList<IRemoteServiceCallBack>();
private int mValue = 0;
private NotificationManager mNM;
@Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
mHandler.sendEmptyMessage(REPORT_MSG);
}
private void showNotification() {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, NotificationActivity.class), 0);
Notification.Builder builder = new Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("服务已经启动")
.setContentIntent(contentIntent)
.setContentTitle("Remote Service")
.setContentText("点击后打开一个Activity")
.setWhen(System.currentTimeMillis());
Notification noti = builder.build();
mNM.notify(R.string.hello_world, noti);
}
//实现需要在客户端调用的功能
private IRemoteService.Stub mBinder = new IRemoteService.Stub() {
@Override
public void unRegisterCallback(IRemoteServiceCallBack cb)