Showing posts with label Broadcast Receiver. Show all posts
Showing posts with label Broadcast Receiver. Show all posts

Monday, July 8, 2013

BOOT_COMPLETED BroadcastReceiver In Android

Android BootReciever


Many a time We need to perform some task when Device/Mobile finish it's booting process.
For Example giving notification that "SIM has been Changed" etc.

For this we need a Broadcast  receiver that should receive "BOOT_COMPLETED" broadcast. We must know  that when a device finishes booting Android System sends "BOOT_COMPLTED" broadcast.

Registering the BootReciever in android manifest file


<receiver android:name=".BootReceiver">
                        <intent-filter>
                                <action android:name="android.intent.action.BOOT_COMPLETED" />
                                <category android:name="android.intent.category.HOME" />
                        </intent-filter>
   </receiver>



and do not forget to add the following permission in manifest .

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

this permission is required to listen/reverie the BOOT_COMPLETED action



BootRecieAndroidvr In

BootReceiver.java  

 

public class BootReceiver extends BroadcastReceiver
{
      
            public void onReceive(Context context, Intent intent)
            {
               
                   // Your code to execute when Boot Completd

                   Toast.makeText(context, "Booting Completed", Toast.LENGTH_LONG).show();
            }
}
                     
           
The onRecieve() method of BootReceiver will execute when boot completes, so wee need to write the code inside onReceive() method.





Monday, June 24, 2013

Detect Missed Call In Android

How to detect a Missed Call in Android



Prerequisite:You should know how to handle Incoming Call. if not, read the post  Handle Incomig Calls using BroadCastReceiver

How to approach :
whenever there as an incoming Phone goes in "RINGING" state, and if the person has not picked/received the call Phone Rings till a particular time and then goes in "IDLE" state.   So we have to monitor the Phone State and check the State accordingly.

Permission Required: 

Following permission is required to listen/monitor the Phone State.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Declare the above permission in manifest file.

Listening Phone State:


We use a BroadcastReceiver class that will monitor the Phone State, whenever there is a change in Phone State, the onReceive() method of BroadcasrReceiver will be called, and in onReceivee(),  we check for the condition, See the Code below

do not forget to register the BroadcastReceiver in manifest  (see the manifest file at the bottom )


IncommingCallReceiver.java


public class IncommingCallReceiver extends BroadcastReceiver
 {
   
      static boolean ring=false;
      static boolean callReceived=false;
     
     
      @Override
      public void onReceive(Context mContext, Intent intent)
      {
         
             // Get the current Phone State
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
           
            if(state==null)
                return;

            // If phone state "Rininging"
            if(state.equals(TelephonyManager.EXTRA_STATE_RINGING))
            {           
                      ring =true;
                     // Get the Caller's Phone Number
                     Bundle bundle = intent.getExtras();
                     callerPhoneNumber= bundle.getString("incoming_number");
              }



             // If incoming call is received
            if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
             {
                    callReceived=true;
              }


             // If phone is Idle
            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
            {
                      // If phone was ringing(ring=true) and not received(callReceived=false) , then it is a missed call
                       if(ring==true&&callReceived==false)
                       {
                                Toast.makeText(mContext, "It was A MISSED CALL from : "+callerPhoneNumber, Toast.LENGTH_LONG).show();
                       }
          }
       
}






 Your manifest should look like follows

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.missedcall"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
   
       <!--  declare the permission -->
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
   

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
              
        <!-- Register the Broadcast receiver  -->
        <receiver android:name=".IncommingCallReceiver" android:enabled="true">
            <intent-filter>
                    <action android:name="android.intent.action.PHONE_STATE" />
                </intent-filter>
           </receiver>
    </application>

</manifest>






Monday, June 3, 2013

Boot Reciever in Android

Android BootReciever


Many a time We need to perform some task when Device/Mobile finish it's booting process.
For Example giving notification that "SIM has been Changed" etc.

For this we need a Broadcast  receiver that should receive "BOOT_COMPLETED" broadcast. We must know  that when a device finishes booting Android System sends "BOOT_COMPLTED" broadcast.

Registering the BootReciever in android manifest file


<receiver android:name=".BootReceiver">
                        <intent-filter>
                                <action android:name="android.intent.action.BOOT_COMPLETED" />
                                <category android:name="android.intent.category.HOME" />
                        </intent-filter>
   </receiver>



and do not forget to add the following permission in manifest .

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

this permission is required to listen/reverie the BOOT_COMPLETED action



BootRecieAndroidvr In

BootReceiver.java  

 

public class BootReceiver extends BroadcastReceiver
{
      
            public void onReceive(Context context, Intent intent)
            {
               
                   // Your code to execute when Boot Completd

                   Toast.makeText(context, "Booting Completed", Toast.LENGTH_LONG).show();
            }
}
                     
           
The onRecieve() method of BootReceiver will execute when boot completes, so wee need to write the code inside onReceive() method.





Tuesday, May 28, 2013

Using Alarm Manger in Android

AlarmManager

Many a times we want some task to be performed at some later time in future.
For Example: In SMS Scheduler we want a SMS to be send at some later time, or Task Reminder in which we want to be reminded  about a task at a particular time, to implement all these things we use AlramManager class.

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted. 

                 The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.


AlarmManager Example

In the example I will schedule an alarm to send SMS at a particular time in future.
We have two classes
1: MainAcitvity: in this class, we will schedule the alarm to be triggered at particular time .
2: AlarmReciever: when the alarm triggers at scheduled time , this class will receive the alarm, and send the SMS.

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method.


Permission Required
we need <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>  permission to use the AlarmManger in our application, so do not forget to declare the permission in manifest file

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.learnandroideasily.blogspot"
    android:versionCode="1"
    android:versionName="1.0" >

            <uses-sdk android:minSdkVersion="8"
                             android:targetSdkVersion="17" />
             <!-- permission required to use Alarm Manager -->
            <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
            <!-- permission required to Send SMS -->
            <uses-permission android:name="android.permission.SEND_SMS"/>
   
            <application
                     android:icon="@drawable/ic_launcher"
                     android:label="Demo App" >
                    <activity
                               android:name=".MainActivity"
                               android:label="Demo App" >
                              <intent-filter>
                                           <action android:name="android.intent.action.MAIN" />

                                           <category android:name="android.intent.category.LAUNCHER" />
                              </intent-filter>
                   </activity>
               <!-- Register the Alarm Receiver -->
                   <receiver android:name=".AlarmReciever"/>
           
         </application>
</manifest>





main.xml





<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Alarm Manager Example"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_marginTop="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Schedule The Alarm"
        android:onClick="scheduleAlarm"/>

</LinearLayout>



MainActivity.java






public class MainActivity extends Activity
{

       @Override
       public void onCreate(Bundle savedInstanceState)
      {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

      }

    public void scheduleAlarm(View V)
    {
            // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time, 

            // we fetch  the current time in milliseconds and added 1 day time
            // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day       
            Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;


            // create an Intent and set the class which will execute when Alarm triggers, here we have

            // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
            // alarm triggers and 
            //we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
            Intent intentAlarm = new Intent(this, AlarmReciever.class);
      
            // create the
AlarmManager   object
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


            //set the alarm for particular time
            alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
            Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
        
    }

}

AlarmReciever.java







public class AlarmReciever extends BroadcastReceiver
{
         @Override
            public void onReceive(Context context, Intent intent)
            {
                    // TODO Auto-generated method stub
               
                   
                    String phoneNumberReciver="9718202185";// phone number to which SMS to be send
                    String message="Hi I will be there later, See You soon";// message to send

                    SmsManager sms = SmsManager.getDefault();
                    sms.sendTextMessage(phoneNumberReciver, null, message, null, null);

                    // Show the toast  like in above screen shot
                    Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
                  
               
             }
      

}



 

 

Advance Android Topics


                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events 



More Android Topics:



Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android



Thursday, May 9, 2013

Incoming Call Broadcast Reciever


Learn Android Development


In previous I discussed about how to handle incoming call or how to listen for Incoming call using Activity, In this post I will discuss the same using Broadcast Receiver.

Broadcast Receiver is  better way than Activity to listen for Incoming Calls.

So declare the Permission and Receiver in Manifest

Permission Required:

 <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Declare the receiver and register it to listen "android.intent.action.PHONE_STATE"  action

android.manifest 


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.incomingcallreciever"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
   
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       
       
        <receiver android:name=".IncommingCallReceiver" android:enabled="true">
            <intent-filter>
                                     <action android:name="android.intent.action.PHONE_STATE" />
                </intent-filter>
           </receiver>

    </application>

</manifest>







Incoming Call Receiver




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


 public class IncommingCallReceiver extends BroadcastReceiver
 {
   
      Context mContext;
     
     
      @Override
      public void onReceive(Context mContext, Intent intent)
      {
          try
          {
          
              String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

          
           
              if(state.equals(TelephonyManager.EXTRA_STATE_RINGING))
              {
                   Toast.makeText(mContext, "Phone Is Ringing", Toast.LENGTH_LONG).show();
                   // Your Code
              }
             
              if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
              {
                   Toast.makeText(mContext, "Call Recieved", Toast.LENGTH_LONG).show();
                       // Your Code
              }
             
              if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
              {
               
                  Toast.makeText(mContext, "Phone Is Idle", Toast.LENGTH_LONG).show();
                      // Your Code
               
              }
          }
          catch(Exception e)
          {
              //your custom message
          }
      
     }
     
}






     
     
   

 

 

 

Advance Android Topics


                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events 



More Android Topics:



Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android



Wednesday, May 1, 2013

Broadcast Reciever in Android


Broadcast  Reciever

A broadcast receiver listens for relevant broadcast messages to trigger an event. Some
examples of broadcasted events already sent from the OS are

Battrey Low
SMS Recieved
Boot Completed   etc


Type of Broadcasts: 

  • Normal broadcasts are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time.
  • Ordered broadcasts are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order. 

Registering Broadcast Receivers in  Manifest  file


All Broadcast Receivers must be registered in Android Manifest file.

here I will discuss about two Broadcast

BOOT_COMPLETED   :  is delivered when device finish Booting process  
SMS_RECEIVED      :   is delivered when da new SMS is Recieved.

BOOT_COMPLETED


 <receiver android:name=".BootReceiver">
                        <intent-filter>
                                <action android:name="android.intent.action.BOOT_COMPLETED" />
                                <category android:name="android.intent.category.HOME" />
                        </intent-filter>
   </receiver>


SMS_RECEIVED



 <receiver android:name=".SMSReciever">
            <intent-filter  android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
              
            </intent-filter>

 </receiver>


We  also need to declare following permission  in manifest  to Receive these Broadcasts

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>


Now we need to create  Java class to handle these events.
For this we need to Extend  BroadcastReceiver    class and override   onReceive()  method.

inside onReceive() method we write the code to handle the events  like  when a new SMS received or Device  finish Booting Process.

BroadcastReceiver Example:

In this example we have cerated a BroadcastReceiver which will receive the SMS

first we Implement SMSReciever class
in this , we will extract the Message Body and the Senders Contact Number from received SMS

here variable  messageReceived will contain the message body.

BroadCastReceiver Class


public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String messageReceived = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                messageReceived += msgs[i].getMessageBody().toString();
                messageReceived += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, messageReceived, Toast.LENGTH_SHORT).show();
        }                         
    }
}
  
To get the Sender's Number use 
msgs.getOriginatingAddress ()     
 
 
More Post  following:  
1: Configuring Eclipse for Android Development 2: Understanding Android Manifest File of your android app 3: Understanding Layouts in Android 4: Using Buttons and EditText in Android  5:  Using CheckBoxes in Android  6:  Sending Data from One Activity to Other in Android 7Using AutoCompleteTextView in Android 8: How to Send SMS in AndroidHow To Receive SMS 10: Notifications In Android 11: How To Vibrate The Android Phone 12: Working With Alert Dialog 13: Adding Radio Buttons In Dialog 14:  Adding Check Boxes In Dialog 15: Creating Customized Dialogs in Android 16: Using TimePickerDialog and DatePickerDialog In android 17: Using Telephony Manager In Android 18: How To Handle Incoming Calls in Android 19: How to Forward an Incoming Call In Android 20 :Working With Menu: Creating Option Menu 21: Working With Menu: Creating Context Menu In Android