[英]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.