user2725921 user2725921 - 4 months ago 18
Java Question

I would like my application that runs in the background was not closed by Android

My application has a service that performs a get in the especific URL every 30 seconds. The service is so configured in AndroidManifest.xml:

<receiver
android:name="com.analisesistemas.taxiweb.android.alarm.MyAlarmReceiver"
android:process=":remote" >
</receiver>
<service
android:name="com.suporte.motoweb.chegaja.MyTestService"
android:exported="false" />


The service starts this way by my application:

// Setup a recurring alarm every half minute
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);

// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // alarm is set right away

AlarmManager alarm = (AlarmManager) this.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, TIMER, pIntent);
}


The method scheduleAlarm() is called in onCreate() of my main Activity.

The problem is that when I press the home button (to minimize my app) so I can use other apps like facebook and instagram ... I notice that
my application stops running (android closed my application likely to save memory).

Really I've tried every way, but Android closed my app when it runs in the background. Not immediately, it is after a few minutes!

How can I prevent my app is terminated by the Android operating system ?? I need to leave it running indefinitely !! :(

thank ever since attention

Answer

According to your requirement instead of Sticky Service I would recommend you to use GCM Network Manager which uses JobSchedular API for Lollipop and upper version and similar compatible way for lower version of android as well. For Periodic Task it would do all the difficult steps for you and you can mainly concentrate on Business logic.

PeriodicTask task = new PeriodicTask.Builder()
        .setService(MyTaskService.class)
        .setTag(TASK_TAG_PERIODIC)
        .setPeriod(30L)
        .build();

mGcmNetworkManager.schedule(task);
Comments