I would like to create a (test) app that executes a command every hour in the background (for example, edit a file or show a debug message).
Assuming that the app starts with system boot
- How can I do this?
- The app must remain running always?
I would like to create a (test) app that executes a command every hour in the background (for example, edit a file or show a debug message).
Assuming that the app starts with system boot
Please use alarmmanager using service functionality to achieve this.
for eg:
private void setAlarmManager() {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long l = new Date().getTime();
if (l < new Date().getTime()) {
l += 86400000; // start at next 24 hour
}
am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000
}
To Make your app start up when the devices boot completes You have to create a Class that extends Receiver. In the manifest Declare your class like this
<receiver android:name=".ClassName">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
And don't forget to use the permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Write the following to your Receiver class, onReceive Override method
Intent intent= new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
If you want to Run something in your background use Services