[英]Pass objects to IntentService from activity
为了节省电池电量,我决定使用“新的”融合位置。 但是,我需要将一些参数传递到接收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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.