Sending an object to a service through Intent without binding

后端 未结 3 1295
悲哀的现实
悲哀的现实 2021-02-13 05:07

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...

3条回答
  •  清酒与你
    2021-02-13 06:09

    You can call startService(Intent) like this:

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

    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
    
        }
    
    }
    

    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");
    

    That's all :)

提交回复
热议问题