Wednesday, January 29, 2014

Using alarms : Android tutorial

Program description:

This program will demo how to create alarms with broadcast receiver.

This program has one activity and one static broadcast receiver. Activity has a button, on clicking that we will set an alarm which will expire after 5 seconds from now. Once alarm is triggered it will send a broadcast with action "com.techpalle.action.ALARM_RECEIVER".
Once broadcast receiver is triggered, it will show a toast message "alarm tirggered".

In order to send a broadcast by using alarms, here we will use pending intents.

Pending intent: It is used to perform intent operations at future point of time on our behalf by some one else (mostly by alarm manager or notification manager).

Broadcast will be send after 5 seconds from the time of button click. It will be send by alarm manager. Since we are not sending broadcast immediately, and it is sent after 5 seconds. So our intent to send broadcast will be pending till then. That's why it is called as pending intent.

Steps to do this alarm program with broadcast receiver in android:
1. Create a broadcast receiver that will be triggered/ called after 5 seconds.
2. Come to activity java file, Create alarm manager object by using getSystemService() method.
3. Create intent to send a broadcast.
4. Create pending intent to shoot a broadcast from above created intent.
5. set the alarm for next 5 seconds by using alarm manager and pass pending intent.

First Activity:

package com.techpalle.b15_alarms;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 Button b;
 AlarmManager am;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  b = (Button) findViewById(R.id.button1);
  //step1 : create alarm manager
  am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    //a. create intent
    Intent in = new Intent();
    in.setAction("com.techpalle.action.ALARM_RECEIVER");
    //b. create pending intent
    PendingIntent pi = PendingIntent.getBroadcast(
      getApplicationContext(), 
      0, 
      in, 
      0);
    //c. set alarm for 5 seconds.
    am.set(AlarmManager.RTC_WAKEUP, 
      System.currentTimeMillis()+5000, 
      pi);
    
    
   }
  });
 }
}

Broadcast receiver 
File name : AlarmRecvr.java

package com.techpalle.b15_alarms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmRecvr extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
     Toast.makeText(context, "Got the alarm..", 0).show();
 }
}

xml file for first activity 
File name : activity_main.xml
 <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:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".MainActivity" >  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_alignParentTop="true"  
     android:layout_marginLeft="24dp"  
     android:layout_marginTop="17dp"  
     android:text="Send broadcast after 5 seconds" />  
 </RelativeLayout>  

Manifest file
File name : AndroidManifest.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.techpalle.b15_alarms"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk  
     android:minSdkVersion="8"  
     android:targetSdkVersion="17" />  
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name="com.techpalle.b15_alarms.MainActivity"  
       android:label="@string/app_name" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
     <receiver android:name="AlarmRecvr">  
       <intent-filter >  
         <action android:name="com.techpalle.action.ALARM_RECEIVER"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?

1 comment: