在服务中我填充了一个ArrayList,然后我返回到调用活动:
在服务中(此处,resultArrayList包含项目且属于类ArrayList<MyObjs>
):
public class DataFetchService extends BaseService {
@Override
protected void onHandleIntent(final Intent intent) {
super.onHandleIntent(intent);
// Do some work here that populates resultArrayList...
final Bundle bundle = new Bundle();
bundle.putSerializable(BaseService.RESULT_OBJ, resultArrayList);
message.setData(bundle);
try {
final Messenger messenger = startIntent.getParcelableExtra(BaseService.PARAM_MESSENGER);
messenger.send(message);
} catch (RemoteException e) {
L.p("Help!");
}
来自BaseService:
public class BaseService extends IntentService {
protected ArrayList<MyObjs> resultArrayList = new ArrayList<>();
// Yada yada...
在活动的handleMessage()中:
@Override
public boolean handleMessage(final Message msg) {
final Bundle bundle = msg.getData();
@SuppressWarnings("unchecked")
final ArrayList<MyObjs> nodes = (ArrayList<MyObjs>) bundle.getSerializable(BaseService.RESULT_OBJ);
if (nodes == null) {
//App never enters this
return
}
if (nodes.size() == 0) {
// Always enters here!
// If I set a breakpoint here, the IDE tells me nodes size is 1
}
奇怪的是,如果我在if (nodes.size == 0) {
代码中设置断点,IDE会显示nodes
确实包含项目(大小= 1,我可以展开它并查看变量),即使它进入了那个。
知道可能是什么问题吗?这可能是其他服务将数据发送回handleMessage()的竞争条件吗?
答案 0 :(得分:0)
我不确定此错误的原因,但在从服务发送之前创建新的ArrayList<>
似乎可以解决此问题。
所以以下内容使其有效:
final Bundle bundle = new Bundle();
// Created this new ArrayList
final ArrayList<MyObjs> newArrayList = new ArrayList<>();
// Add items to the new ArrayList
newArrayList.addAll(resultArrayList);
// Send the new ArrayList and NOT the other one.
bundle.putSerializable(BaseService.RESULT_OBJ, newArrayList);
message.setData(bundle);
try {
final Messenger messenger = startIntent.getParcelableExtra(BaseService.PARAM_MESSENGER);
messenger.send(message);
} catch (RemoteException e) {
L.p("Help!");
}