我目前正在开发一个需要从服务器获取XML数据的应用程序,解析它并将其存储在数据库中。我已经为它创建了一个intent服务,它工作正常。但是警报管理员不允许我在用户登录后立即立即呼叫该服务。
我需要的是在第一次通话时立即拨打服务,然后根据警报管理员的时间表在后台进行轮询。我不想为第一次运行条件重新编写相同的代码。
有没有办法实现这个目标?
我的服务代码如下。
public AdChangeCheckerService() {
// Used to name the worker thread, important only for debugging.
super(TAG);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try {
boolean isNetwork = Utility.isNetworkAvailable(getApplicationContext());
if (isNetwork) {
readAndStoreAds();
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
private void readAndStoreAds() throws IOException, XmlPullParserException {
String returned = null;
URL url = new URL(urll);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
try {
int statusCode = urlConnection.getResponseCode();
InputStream in;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
in = new BufferedInputStream(urlConnection.getInputStream());
} else {
in = new BufferedInputStream(urlConnection.getErrorStream());
}
//converting inputstrream to string
returned = readStream(in);
storeAds(returned);
} finally {
//regardkless of success or faliure we disconnect the connection
urlConnection.disconnect();
}
} else {
urlConnection.disconnect();
}
}
private void storeAds(String received) throws IOException, XmlPullParserException {
InputStream stream = new ByteArrayInputStream(received.getBytes());
//setting up xml pullparser
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(stream, null);
XMLParserForAds xml_parse = new XMLParserForAds(getApplicationContext());
xml_parse.readFeedAndStore(parser);
}
private String readStream(InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
return (result.toString());
}
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = new Intent(context, AdChangeCheckerService.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (isOn) {
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), POLL_INTERVAL, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
}