Pass objects to IntentService from activity

2019-04-17 06:42发布

To save battery in my app I decided to use the "new" Fused locations. However I need to pass some parameters into the service which receives GPS updates. The way It's done below would work (putExtras(...)), but I would need to make a lot of classes Serializable/Parseable, which would be a pain.

I have searched around and found some other way using Binder, but can't figure out how to get it to work. Is using Binder the only way or is there another?

If anything is unclear, please tell. Thank you.

public class LocationService extends IntentService {
    ...
    public LocationService(StartActivity startActivity, DatabaseSQLite db, HomeFragment homeFragment) {
        super("Fused Location Service");
        ...
    }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
   db = (DatabaseSQLite) intent.getExtras().get("DatabaseSQLite");

   ...
   return START_REDELIVER_INTENT;

    }
}

And this is how It's used in my activity:

@Override
    public void onConnected(Bundle bundle) {
        mIntentService = new Intent(this, LocationService.class);
        mIntentService.putExtra("DatabaseSQLite", database);
        ...
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

}

1条回答
别忘想泡老子
2楼-- · 2019-04-17 07:25

You should check out https://github.com/greenrobot/EventBus

Examples can be found here: http://awalkingcity.com/blog/2013/02/26/productive-android-eventbus/

Basically lets you do stuff like:

@Override
    public void onConnected(Bundle bundle) {
        mIntentService = new Intent(this, LocationService.class);

        // could be any object
        EventBus.getDefault().postSticky(database);
        ...
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

}

And whenever you need the object

public class LocationService extends IntentService {
    ...
    public LocationService(StartActivity startActivity, DatabaseSQLite db, HomeFragment homeFragment) {
        super("Fused Location Service");
        ...
    }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {

   // could also be in Broadcast Receiver etc..
   db = EventBus.getDefault().getStickyEvent(DatabaseSQLite.class); 

   ...
   return START_REDELIVER_INTENT;

    }
}

Not only is it simpler, this link also shows that it outperforms other methods: http://www.stevenmarkford.com/passing-objects-between-android-activities/

查看更多
登录 后发表回答