从活动将对象传递给IntentService

为了节省我的应用程序中的电池,我决定使用“新”融合位置。 但是我需要将一些参数传递给接收GPS更新的服务。 它在下面完成的方式可以工作( putExtras(...) ),但我需要制作很多类Serializable / Parseable,这将是一个痛苦。

我已经四处搜索并找到了使用Binder的其他方法,但无法弄清楚如何让它工作。 是使用Binder的唯一途径还是另一种?

如果有任何不清楚的地方,请告诉我们。 谢谢。

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

这就是它在我的活动中的用法:

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

你应该看看https://github.com/greenrobot/EventBus

可以在此处找到示例: http : //awalkingcity.com/blog/2013/02/26/productive-android-eventbus/

基本上可以让你做的事情:

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

无论何时你需要这个对象

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

它不仅更简单,而且还表明它优于其他方法: http : //www.stevenmarkford.com/passing-objects-between-android-activities/