Android Api Demos登顶之路(五十六)Service Remote Service

该博客介绍如何在Android中实现跨进程的Service通信,通过RemoteCallbackList实现服务端对客户端的回调功能。文章详细展示了服务端的ProcessId.aidl、IRemoteService.aidl、IRemoteServiceCallBack.aidl、RemoteService.java以及客户端的activity_main布局文件和MainActivity的设置过程。
摘要由CSDN通过智能技术生成

这个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)
                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值