简体   繁体   中英

Pass objects to IntentService from activity

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

}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM