you can create background service and call that by AlarmManager
1- you have to create a BroadcastReceiver class for calling by
AlarmManager
public class AlarmReceiver extends BroadcastReceiver
{
/**
* Triggered by the Alarm periodically (starts the service to run task)
* @param context
* @param intent
*/
@Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, AlmasService.class);
i.putExtra("foo", "AlarmReceiver");
context.startService(i);
}
}
2-you have to create a IntentService class for calling by
AlarmReceiver
public class AlmasService extends IntentService
{
public Context context=null;
// Must create a default constructor
public AlmasService() {
// Used to name the worker thread, important only for debugging.
super("test-service");
}
@Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
}
@Override
protected void onHandleIntent(Intent intent) {
context=this;
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
String val = intent.getStringExtra("foo");
// Do the task here
Log.i("MyTestService", val);
}
}
3- you have to add AlarmReceiver as receiver and AlmasService as service on manifest
<service
android:name=".ServicesManagers.AlmasService"
android:exported="false"/>
<receiver
android:name=".ServicesManagers.AlmasAlarmReceiver"
android:process=":remote" >
</receiver>
4-now you can start service and call AlarmManager on MainActivity
public class MainActivity extends AppCompatActivity
{
public static final int REQUEST_CODE = (int) new Date().getTime();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleAlarm();
}
public void scheduleAlarm()
{
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AlmasAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(
this, REQUEST_CODE, 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) 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.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, (long) (1000 * 60), pIntent);
}
}