Download presentation
Presentation is loading. Please wait.
1
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager 1
2
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Android Alarm With Notification Android AlarmManager allows you to access system alarm. By the help of Android AlarmManager in android, you can schedule your application to run at a specific time in the future. It works whether your phone is running or not. The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep the phone until broadcast is handled. Find the code snippet how to use it. 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
3
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
There are four types of alarm ELAPSED_REALTIME ELAPSED_REALTIME_WAKEUP RTC RTC_WAKEUP 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
4
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Find some methods which are used to schedule alarms. These methods are based on exact, inexact time of execution and repeating or single execution. set(int type, long triggerAtMillis, PendingIntent operation) : Schedules the alarm and if there is already an alarm by the intent then previous one will be canceled. It allows executing only one time. setExact(int type, long triggerAtMillis, PendingIntent operation) : It behaves same as set() but it does not allow OS to adjust time. The alarm will fire on exact time. setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) : It behaves same as set() but repeats for the given interval of time. setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) : Same as setRepeating() but the executing time will not be exact. setWindow(int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation) : Executes within a given window of time and works same as set(). It can be used for strict ordering of execution in case of multiple alarms. Now find some constants which gives time in milliseconds and are used for repeating alarm interval. These are INTERVAL_DAY , INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_DAY , INTERVAL_HALF_HOUR , INTERVAL_HOUR . 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
5
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Find some sample of alarm execution. The below alarm will execute after 15 minutes and repeat after every 15 minutes. alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, AlarmManager.INTERVAL_FIFTEEN_MINUTES, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); The below alarm will execute only one time after 15 minute. alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 15* 60 * 1000, pendingIntent); 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
6
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
PendingIntent android.app.PendingIntent is a reference of a token maintained by system describing the original data used to retrieve it. PendingIntent can be initialized by using below methods of its own 1. getActivity(Context, int, Intent, int) 2. getActivities(Context, int, Intent[], int) 3. getBroadcast(Context, int, Intent, int) 4. getService(Context, int, Intent, int) All the above methods returns the instance of PendingIntent. If using alarm, we do as below. 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
7
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
WakefulBroadcastReceiver android.support.v4.content.WakefulBroadcastReceiver is a helper class that receives a device wakeful event. We override onReceive() method where we can call our service or perform our task. In our case we will play alarm. WakefulBroadcastReceiver uses wake lock, so we must provide WAKE_LOCK permission in AndroidManifest.xml.WakefulBroadcastReceiver is implemented as How to Cancel Alarm Clock To cancel alarm, AlarmManager provides cancel() method. We can use it as follows. 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
8
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Example Code: create three buttons start repeating timer, cancel repeating timer and one-time timer in the layout file. These buttons are attached with methods i.e startRepeatingTimer, cancelRepeatingTimer and onetimeTimer respecitively. These methods will be defined in the Activity class. The layout file is shown below(activity_alarm_manager.xml). 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
9
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
BroadcastReciever the BroadcastReciever which handles the intent registered with AlarmManager. In the given class onReceive() method has been defined. This method gets invoked as soon as intent is received. Once we receive the intent we try to get the extra parameter associated with this intent. This extra parameter is user-defined i.e ONE_TIME, basically indicates whether this intent was associated with one-time timer or the repeating one. Helper methods have also been defined, which can be used from other places with the help of objects i.e setAlarm(), cancelAlarm() and onetimeTimer() methods. These methods can also be defined somewhere else to do operation on the timer i.e set, cancel, etc. To keep this tutorial simple, we have defined it in BroadcastReceiver. 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
10
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
setAlarm(): This method sets the repeating alarm by use of setRepeating() method. setRepeating() method needs four arguments: type of alarm, trigger time: set it to the current time interval in milliseconds: in this example we are passing 5 seconds ( 1000 * 5 milliseconds) pending intent: It will get registered with this alarm. When the alarm gets triggered the pendingIntent will be broadcasted. cancelAlarm(): This method cancels the previously registered alarm by calling cancel() method. cancel() method takes pendingIntent as an argument. The pendingIntent should be matching one, only then the cancel() method can remove the alarm from the system. onetimeTimer(): This method creates an one-time alarm. This can be achieved by calling set() method. set() method takes three arguments: type of alarm trigger time pending intent 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
11
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
BroadcastReciever coding import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.PowerManager; import android.widget.Toast; public class AlarmManagerBroadcastReceiver extends BroadcastReceiver { final public static String ONE_TIME = "onetime"; public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG"); //Acquire the lock wl.acquire(); //You can do the processing here. Bundle extras = intent.getExtras(); StringBuilder msgStr = new StringBuilder(); if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){ //Make sure this intent has been sent by the one-time timer button. msgStr.append("One time Timer : "); } Format formatter = new SimpleDateFormat("hh:mm:ss a"); msgStr.append(formatter.format(new Date())); Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show(); //Release the lock wl.release(); } 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
12
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
BroadcastReciever coding public void SetAlarm(Context context) { AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); intent.putExtra(ONE_TIME, Boolean.FALSE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); //After after 5 seconds am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); } public void CancelAlarm(Context context) PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); public void setOnetimeTimer(Context context){ AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); intent.putExtra(ONE_TIME, Boolean.TRUE); am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi); } 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
13
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
manifest file WAKE_LOCK permission is required because the wake lock is being used while processing in onReceive() method present in AlarmManagerBroadcastReceiver class. AlarmManagerBroadcastReceiver has been registered as broadcast receiver. <manifest android:versioncode="1" android:versionname="1.0" package="com.rakesh.alarmmanagerexample" xmlns:android=" <uses-sdk android:minsdkversion="10" android:targetsdkversion="15"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application <activity android:name="com.rakesh.alarmmanagerexample.AlarmManagerActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver"> </receiver> </application> </manifest> 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
14
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
activity class code import com.rakesh.alarmmanagerexample.R; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import android.support.v4.app.NavUtils; public class AlarmManagerActivity extends Activity { private AlarmManagerBroadcastReceiver alarm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm_manager); alarm = new AlarmManagerBroadcastReceiver(); } protected void onStart() { super.onStart(); } public void startRepeatingTimer(View view) { Context context = this.getApplicationContext(); if(alarm != null){ alarm.SetAlarm(context); }else{ Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } Here in this class we create an instance of AlarmManagerBroadcastReciever which will help us to access setAlarm(), cancelAlarm() and setOnetime(). Rest of the code is easy to understand. 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
15
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
activity class code public void cancelRepeatingTimer(View view){ Context context = this.getApplicationContext(); if(alarm != null){ alarm.CancelAlarm(context); }else{ Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } } public void onetimeTimer(View view){ alarm.setOnetimeTimer(context); public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu); return true; } 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
16
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Screen Shot 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
17
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Create Activity, Alarm Receiver and Time Picker MainActivity.java import java.util.Calendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends FragmentActivity{ private static int timeHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE); TextView textView1; private static TextView textView2; public static TextView getTextView2() { return textView2; } AlarmManager alarmManager; private PendingIntent pendingIntent; @Override 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
18
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
MainActivity.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); textView1 = (TextView)findViewById(R.id.msg1); textView1.setText(timeHour + ":" + timeMinute); textView2 = (TextView)findViewById(R.id.msg2); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0); OnClickListener listener1 = new OnClickListener() { public void onClick(View view) { textView2.setText(""); Bundle bundle = new Bundle(); bundle.putInt(MyConstants.HOUR, timeHour); bundle.putInt(MyConstants.MINUTE, timeMinute); MyDialogFragment fragment = new MyDialogFragment(new MyHandler()); fragment.setArguments(bundle); FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.add(fragment, MyConstants.TIME_PICKER); transaction.commit(); } }; 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
19
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
MainActivity.java Button btn1 = (Button)findViewById(R.id.button1); btn1.setOnClickListener(listener1); OnClickListener listener2 = new OnClickListener() { public void onClick(View view) { textView2.setText(""); cancelAlarm(); } }; Button btn2 = (Button)findViewById(R.id.button2); btn2.setOnClickListener(listener2); class MyHandler extends Handler { @Override public void handleMessage (Message msg){ Bundle bundle = msg.getData(); timeHour = bundle.getInt(MyConstants.HOUR); timeMinute = bundle.getInt(MyConstants.MINUTE); textView1.setText(timeHour + ":" + timeMinute); setAlarm(); private void setAlarm(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, timeHour); calendar.set(Calendar.MINUTE, timeMinute); alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } private void cancelAlarm() { if (alarmManager!= null) { alarmManager.cancel(pendingIntent); 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
20
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
AlarmReceiver.java package com.concretepage.android; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.content.WakefulBroadcastReceiver; public class AlarmReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { MainActivity.getTextView2().setText("Enough Rest. Do Work Now!"); Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); Ringtone ringtone = RingtoneManager.getRingtone(context, uri); ringtone.play(); } } } 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
21
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
MyDialogFragment.java import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.DialogFragment; import android.widget.TimePicker; public class MyDialogFragment extends DialogFragment { private int timeHour; private int timeMinute; private Handler handler; public MyDialogFragment(Handler handler){ this.handler = handler; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle bundle = getArguments(); timeHour = bundle.getInt(MyConstants.HOUR); timeMinute = bundle.getInt(MyConstants.MINUTE); TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { timeHour = hourOfDay; timeMinute = minute; Bundle b = new Bundle(); b.putInt(MyConstants.HOUR, timeHour); b.putInt(MyConstants.MINUTE, timeMinute); Message msg = new Message(); msg.setData(b); handler.sendMessage(msg); } }; return new TimePickerDialog(getActivity(), listener, timeHour, timeMinute, false); 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
22
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
MyConstants.java package com.concretepage.android; public abstract class MyConstants { public static final String HOUR = "time_hour"; public static final String MINUTE = "time_minute"; public static final String TIME_PICKER = "time_picker"; } AndroidManifest.xml We must provide permission of WAKE_LOCK and register the receriver. In our case we have to register our AlarmReceiver. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.concretepage.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="19" /> <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> <application android:allowBackup ="false" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".AlarmReceiver"/> </application> </manifest> 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
23
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
mylayout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#D1C4E9" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" <TextView android:layout_width="wrap_content" android:layout_gravity="center" android:textColor="#FF8A80" android:textSize="100sp" android:textColor="#4CAF50" android:textSize="50sp" </LinearLayout> strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Concrete Page</string> <string name="btn_start"> Start </string> <string name="btn_stop"> Stop </string> </resources> 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
24
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Output 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
25
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Thank You 24 July 2018 S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.