我创建了一个IntentService
来将本地数据发送到服务器。
我从两个不同的service
调用此broadcast receivers
。
1)当从连接改变接收器时。
2)上午12点与警报管理员
应用程序打开时工作正常。 但是当应用关闭时无法正常工作。
以下是我的 IntentService
代码。
public class ExpertEventService extends IntentService {
@Inject
Context context;
@Inject
Realm realm;
public ExpertEventService() {
super("ExpertEventService");
Log.e("expertEvent", "service constructor");
// Toothpick.inject(this, Toothpick.openScope(Constants.APPSCOPENAME));
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Toothpick.inject(this, Toothpick.openScope(Constants.APPSCOPENAME));
Log.e("expertEvent", "service started");
RealmResults<AskExpertEventModel> results = realm.where(AskExpertEventModel.class).findAll();
List<AskExpertEventModel> requestList = realm.copyFromRealm(results);
String language = realm.where(LanguageStore.class).equalTo(LanguageStore.ISSELECTED, true).findAll().first().getCode();
String appInstanceCode = Preferences.getAppInstanceCode(context);
String token = Preferences.getToken(context);
Api.userManagement(context).expertEvent(appInstanceCode, token, language, requestList)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new ApiSuccess<EventResponse>() {
@Override
public void call(EventResponse eventResponse) {
Log.e("expertEvent", eventResponse.getStatus());
if (eventResponse.getStatus().equalsIgnoreCase(Constants.Status.STATUS_SUCCESS)) {
Log.e("expertEvent", "sucess");
new RealmDB().deleteEvent();;
}
}
}, new ApiFail() {
@Override
public void httpStatus(HttpErrorResponse response) {
Log.e("expertEvent", response.getError());
}
@Override
public void noNetworkError() {
Log.e("expertEvent", "no network connection");
}
@Override
public void unknownError(Throwable e) {
Log.e("expertEvent", e.getMessage());
}
});
}
}
1)连接器更改时调用接收器
public class NetworkStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("expertEvent", "Connectivity changed");
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
//start service
Log.e("expertEvent", "Connected ");
Intent serviceIntent = new Intent(context,
ExpertEventService.class);
context.startService(serviceIntent);
}
} else {
Log.e("expertEvent", "not connected");
}
}
}
2)上午12点执行
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//call service
Log.e("alarmreceiver","in alarm receiver");
Intent serviceIntent = new Intent(context, ExpertEventService.class);
context.startService(serviceIntent);
}
}