gpt4 book ai didi

java - 将对象从 Activity 传递到 IntentService

转载 作者:行者123 更新时间:2023-12-02 05:33:50 26 4
gpt4 key购买 nike

为了节省应用程序的电池电量,我决定使用"new"Fused 位置。但是我需要将一些参数传递到接收 GPS 更新的服务中。下面完成的方式可以工作(putExtras(...)),但我需要使很多类可序列化/可解析,这将是一个痛苦。

我到处搜索并找到了使用 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;

}
}

这就是它在我的 Activity 中的使用方式:

@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/

关于java - 将对象从 Activity 传递到 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com