I need my Android-App to retrieve the configuration from the server once per hour via http-get.
I'm new to Android, I've been fighting for days ... Finally I made it using AlarmManager. With setInexactRepeating (alarm type RTC_WAKEUP) triggers AlarmReceiverTEST (BroadcastReceiver) and it calls MyTestService (IntentService) that makes the GET call through an AsyncTask.
Before I made several attempts. In both the App stopped working after several alarms:
- Call the AsyncTask from the BroadcastReceiver (without using a Service).
- The alarm triggers a Service directly (through PendingIntent.getService) that the AsyncTask calls.
This is the final code. Please, tell me if I'm doing well ...
1. AndroidManifest.xml I define the receiver and the service:
<receiver android:name="AlarmReceiverTEST" android:enabled="true" />
<service android:name=".MyTestService" android:exported="false" />
2. AlarmReceiverTEST.java Process that triggers the alarm. This starts the MyTestService service:
public class AlarmReceiverTEST extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyTestService.class);
context.startService(service1);
}
}
3. MyTestService.java Make the GET call using an AsyncTask:
public class MyTestService extends IntentService {
public MyTestService() {
super("MyTestService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
new CallAPI_GET().execute();
}
public final String USER_AGENT = "Mozilla/5.0";
public final String GET_URL = "http://www.miservidor.org/api/getConf.php";
public class CallAPI_GET extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String sMessage = "";
try {
String sUrl = GET_URL + "?cfgIni=0&idInstala=" + MyApp.iIdInstala;
URL obj = new URL(sUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode(); // 200?
if (responseCode == HttpURLConnection.HTTP_OK) { // success
// Recuperar missatge del servidor
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
sMessage = response.toString();
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sMessage;
}
@Override
protected void onPostExecute(String sResult) {
super.onPostExecute(sResult);
// Procesar resultado ...
}
}
4. MainActivity.java Main program; I set an alarm with setInexactRepeating, which triggers AlarmReceiverTEST every hour:
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AlarmReceiverTEST.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(),1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every every half hour from this point onwards
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
AlarmManager.INTERVAL_HOUR, pIntent);
Thanks in advance! :)