通过Intent将对象发送到服务而无需绑定 [英] Sending an object to a service through Intent without binding

查看:60
本文介绍了通过Intent将对象发送到服务而无需绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过Intent将对象发送到Android服务,而无需实际绑定到该服务?也许是服务访问对象的另一种方式...

Is is possible to send an object to an Android Service through an Intent without actually binding to the service? Or maybe another way for the Service to access Objects...

推荐答案

您可以像这样调用startService(Intent):

You can call startService(Intent) like this:

MyObject obj = new MyObject();
Intent intent = new Intent(this, MyService.class);
intent.putExtra("object", obj);
startService(intent);

您要发送的对象必须实现Parcelable(您可以参考此 Percelable指南)

The object you want to send must implement Parcelable (you can refer to this Percelable guide)

class MyObject extends Object implements Parcelable {

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        // TODO Auto-generated method stub

    }

}

使用Service,在api级别5及更高版本的onStart()或onStartCommand()方法中,您可以获取该对象:

And with the Service, in the method onStart() or onStartCommand() for api level 5 and newer, you can get the object:

MyObject obj = intent.getParcelableExtra("object");

仅此而已:)

这篇关于通过Intent将对象发送到服务而无需绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆