Android Service 与 Activity使用Pending Intent通信

这篇博客探讨了在Android开发中,如何利用PendingIntent作为桥梁,实现Service与Activity之间的有效通信,详细阐述了Service如何通过PendingIntent将结果回传给调用它的客户端Activity。
摘要由CSDN通过智能技术生成

Android Service 与 Activity使用Pending Intent通信

service使用pending intent返回结果给客户端


我们使用一个activity作为一个客户端,来通过startService()的方法启动一个服务,这个服务的功能很简单,就是去访问客户端指定的Url,然后返回这个url对应的页面的源代码的字符数量。这个例子中,我们是不允许这个服务被绑定的。即我们在onBind()方法中返回null。那么好了,现在我们这个服务不可以被绑定,只可以通过startService()的方法启动,那么此时服务和客户端的通信方式就只有一种了,即通过Pending Intent了。

1.首先自定义我们的服务类:MyService

public class MyService extends Service {
    private ServiceHandler mHandler;
    //内部类
    private final  class ServiceHandler extends Handler{

        public ServiceHandler(Looper looper){
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x1234){
                Log.v("MyService","handleMessage()被调用");

                int charNum = ((String)(msg.obj)).length();
                Bundle bundle = msg.getData();
                PendingIntent client = bundle.getParcelable("receiver");

                Log.v("MyService","字符数为" + charNum);
                Intent intent = new Intent();
                intent.putExtra("CHARNUM",charNum);
                try {
                    client.send(ge
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值