读取事件流可以正常工作(即使在背景,前景中),在后台运行一段时间后,它不会读取任何事件,也不会破坏服务。
需要它在后台阅读事件。我想通过检查是否没有主动阅读事件来恢复活动时恢复阅读事件。目前我正在检查服务是否从getSystemService列表运行。基本上我只是一个事件流阅读器,而不是产生多个流阅读器。 (我知道这是一个糟糕的设计,但现在不是问题)。
private boolean isEventsServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.xxxxx.EventsListenerService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void startReadingEvents() {//gets called from onHandleIntent
URL url = null;
try {
url = new URL(ServerCalls.SERVER_ADDR + "/stream/" + ServerCalls.streamId + eventsRenewPath);
con = (HttpURLConnection) url.openConnection();
inpStream = con.getInputStream();
Scanner inputStream = new Scanner(new InputStreamReader((inpStream)));
inputStream.useDelimiter("\r\n");
boolean keepReading = true;
while(keepReading){
StringBuilder str = new StringBuilder();
String bytes;
while(inputStream.hasNext()){
bytes = inputStream.next();
if(bytes==null) return; //reinitialize
if(bytes.equalsIgnoreCase("")){
break; // stop word reached
}
str.append(bytes);
str.append("\n");
}
if(str.length()>0) {
Log.e(Config.ERR_LOG_TAG, "event found andbroadcasting...");
publishEvent(str.toString());
}
else{
keepReading = false;
Log.e(Config.ERR_LOG_TAG, "Empty event found ");
publishEvent(null);
}
}
} catch (IOException | IllegalStateException e) {
Log.e(Config.ERR_LOG_TAG, "Scanner is closed , restarting : "+(3-count));
if(count-->0){ //retry count times.
startReadingEvents();
return;
}
else{
Toast.makeText(getApplicationContext(), "Check your internet connection" , Toast.LENGTH_LONG).show();
}
}
Log.e(Config.ERR_LOG_TAG, "Events listener is stopped ");
return;
}