Saturday, 18 June 2016

Android Broadcastreceiver Tutorial | Broadcastreceiver in Android Example

Hey warriors whats going on guys , In this post I am going to share with you very cool functionality of android system called BroadcastReceiver in android. A broadcast receiver (short receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. so without making more gossips I am going to start with coding.


I am going to create a sample for location broadcast ,it will generate a notification when user will turn on/off  GPS. you can check list of all system Broadcast here .So I am going to make module of steps to complete this tutorial.

  • Create new project in your Android studio. Go to File>>New>>New project
  • Add Broadcast Receiver to your manifest file.
  • Create Receiver class to receive your Broadcast.
  • Generate notification in onReceive of Receiver class you can do anything else. 
1.Create new project in your android studio Go to File>>New>>New project like below image.



2.Add Broadcast Receiver to your manifest file. Since I am making Broadcast for location so i am adding Intent filter for location. add below code to your manifest file inside application tag.

1
2
3
4
5
 <receiver android:name=".MyReciever">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
            </intent-filter>
        </receiver>
In above code .MyReciver is java class i have created to listen broadcast. here is my manifest file.

3.Create a new java class to receive broadcast I am creating this class MyReciever and extend BroadcastReceiver class then it will ask you to implement method onReceive(). like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class MyReciever extends BroadcastReceiver {

    
    @Override
    public void onReceive(Context context, Intent intent) {
       
    }

  

}

4. Inside onReceive() I am using code to check gps is on or off because broadcast only notify that location provider is changed so you to write code to check gps is on or off then generate notification. If you don't know How to create notification in android then check my tutorial notification in android. Here is my complete code of MyRciever class.

Finally we have completed this tutorial you can download complete demo code from below download button. Turn on/off you your gps and you will receive notification.if this post was helpful for your don't forget to comment below because its always motivate us to write new things.

https://codeload.github.com/kundansviet/BroadcastReceiverDemo/zip/master

0 comments:

Post a Comment