So here is another useful thing in Android Development. Today we will see an Android Scheduled Task Example using AlarmManager. Scheduling tasks sometimes are essential. For example, your apps need to execute a particular job daily at a specific time defined by the user. Then we can do it using the AlarmManager in android. So let’s start.
Table of Contents
Android Scheduled Task Example Video
- If you don’t like following written tutorial, then here we have video explanation for you as well. Instead of reading this post you can watch this video to learn the same.
Android Scheduled Task Example using AlarmManager
Creating a new Project
- As always we will be creating a new Android Studio Project. So here I am with my project named AlarmManagerExample.
Building UI
- Inside activity_main.xml we will create the following UI. This is pretty simple we have only a TimePicker and a Button.
- For the above UI you can use the following XML code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context="net.simplifiedlearning.alarmmanagerexample.MainActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical"> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonAlarm" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Set Alarm" /> </LinearLayout> </RelativeLayout> |
Creating a Broadcast Receiver for the Alarm
- We need a Broadcast Receiver to fire the alarm when our app is not running.
Creating BroadcastReceiver
- So create a java class named MyAlarm.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package net.simplifiedlearning.alarmmanagerexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; /** * Created by Belal on 8/29/2017. */ //class extending the Broadcast Receiver public class MyAlarm extends BroadcastReceiver { //the method will be fired when the alarm is triggerred @Override public void onReceive(Context context, Intent intent) { //you can check the log that it is fired //Here we are actually not doing anything //but you can do any task here that you want to be done at a specific time everyday Log.d("MyAlarmBelal", "Alarm just fired"); } } |
Registering BroadcastReceiver
- We also need to register this BroadcastReceiver in the Manifest file. So here is the AndroidManifest.xml file where you need to register your receiver just before the </application> tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedlearning.alarmmanagerexample"> <uses-permission android:name="android.permission.WAKE_LOCK" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- registering the receiver --> <receiver android:name=".MyAlarm" android:enabled="true" android:exported="true" /> </application> </manifest> |
Setting the Alarm
- Now the final step is setting up the Alarm. We will do this inside MainActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package net.simplifiedlearning.alarmmanagerexample; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; public class MainActivity extends AppCompatActivity { //the timepicker object TimePicker timePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting the timepicker object timePicker = (TimePicker) findViewById(R.id.timePicker); //attaching clicklistener on button findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //We need a calendar object to get the specified time in millis //as the alarm manager method takes time in millis to setup the alarm Calendar calendar = Calendar.getInstance(); if (android.os.Build.VERSION.SDK_INT >= 23) { calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0); } else { calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0); } setAlarm(calendar.getTimeInMillis()); } }); } private void setAlarm(long time) { //getting the alarm manager AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); //creating a new intent specifying the broadcast receiver Intent i = new Intent(this, MyAlarm.class); //creating a pending intent using the intent PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); //setting the repeating alarm that will be fired every day am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pi); Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show(); } } |
- Now thats it you can run the application.
- Now after setting the alarm even if you close your application. The method will be fired at the specified time. And you can do anything you want as a scheduled task. Right now it will do nothing and will print a message on log as you can see below.
Android Scheduled Task Example Source Code Download
- If you are having some troubles doing the project. Then here is my source code for you.
[sociallocker id=1372] Android Scheduled Task Example Source Code Download [/sociallocker]
Conclusion
- So you can use AlarmManager to schedule your tasks. But remember only use AlarmManager when you want to execute your task at a specified time. If you want to schedule tasks other than a time constraint then you should use JobScheduler. We will discuss about it in the upcoming posts.
So thats all for this Android Scheduled Task Example guys. Feel free to leave your comments if having any feedbacks or suggestions. If the post helped you please SHARE and give us a LIKE. Thank You 🙂