在android中创建一个空服务是一个好主意吗?
我想创建一个空服务,一旦某个片段打开,该服务将在后台运行-该服务将在后台填充一个数组,但不会在当前(调用片段)中使用: 创建服务的代码:在android中创建一个空服务是一个好主意吗?,android,android-fragments,service,android-service,Android,Android Fragments,Service,Android Service,我想创建一个空服务,一旦某个片段打开,该服务将在后台运行-该服务将在后台填充一个数组,但不会在当前(调用片段)中使用: 创建服务的代码: Intent intent = new Intent(); intent.putExtra(ServiceActions.class.getName(), ServiceActions.GET_LIST_FROM_API); intent.putExtra("api_code_id", "12345");
Intent intent = new Intent();
intent.putExtra(ServiceActions.class.getName(), ServiceActions.GET_LIST_FROM_API);
intent.putExtra("api_code_id", "12345");
managerProvider.getRequestManager().startRetrievalService(intent);
注册和取消注册侦听器:
manager.registerReceiver(backgroundListReceiver , new IntentFilter(ServiceBroadcasts.GET_LIST_FROM_API_RESULT.name()));
manager.unregisterReceiver(backgroundListReceiver );
然后处理接收器:
backgroundListReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean result = extras.getBoolean(ServiceBroadcasts.GET_LIST_FROM_API_RESULT.name());
// DO Nothing here as the list is loading in the background
// and stored in the application class
}
};
我确实在片段中注册和注销了它,我想我会问这样做是正确的还是有其他更好的过程?在这里这样做的原因是,用户选择列表的几率非常高,因此我尝试在用户选择列表之前预加载列表。
在后台处理加载列表的代码:
private void getListInBackground() {
RequestResponse response = RestAPI.getListInBackground();
if (response.isSuccessful()) {
mApp.setBackgroundList(JacksonMapper.deserBackgroundList(response.getResponseString()));
}
Intent broadcast = new Intent(ServiceBroadcasts.GET_LIST_FROM_API_RESULT.name());
broadcast.putExtra(ServiceBroadcasts.GET_LIST_FROM_API_RESULT.name(), response.isSuccessful());
mManager.sendBroadcast(broadcast);
}
您的用例是什么?在调用片段中,我有一个按钮来显示列表,因此我想在选择按钮之前在后台填充该列表。使用服务似乎没有任何意义。您可以获取并填充在单独线程中运行的同一类中的数组。之后,当你按下按钮时,检查数组是空的还是空的。该服务正在调用web api以获取列表。这有什么区别吗?我想你很困惑。在您的问题中,您谈论的是
服务
,但您的代码显示的是广播接收器
,您谈论的是“注册”和“注销”,这是为广播接收器
s而不是服务
s完成的。