Skip to main content

Android BroadcastReceiver


A  Broadcast receiver (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.
For example, applications can register for various events like boot complete or battery low and Android system sends broadcast when specific event occur.Any application can  also create its own  custom broadcasts 
Basics of Broadcast                                                                                                         
Register Broadcast                                                                                                                     
There are two ways to register broadcast receiver-                                                                          

1.Statically ( Manifest-Declared ) : By the receiver can registered via the AndroidManifest.xml file.                                                                                                                                 
2.Dynamically ( Context-Register ): By this register a receiver dynamically via the Context.registerReceiver() method 
Receive Broadcast                                                                                                                           
To be able to receive a broadcast, application have to extends the Broadcastreceiver abstract class and override its onReceiver() method. If the event for which the broadcast receiver has registered  happens, the receiver is called by the Android system.                                                  
Implementation: 

  ADD Permissions in AndroidManifest.xml File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/ap/android"   package="com.ss.broadcastexample">                                                                                                                      
<uses-permission android:name="android.permission.VIBRATE" > </uses-permission>                                               <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>                                                                
<receiver android:name="MyBroadCast" ></receiver>                     
</application>                                                             
 </manifest>                                                   

ADD  These line of Code in MainActivity.java file 
package com.ss.broadcastexample;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    EditText ed_time;
    Button btn_ok;
    @Override    
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed_time = (EditText) findViewById(R.id.time);
        btn_ok = (Button) findViewById(R.id.ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override            
                public void onClick(View view) {
                String time = ed_time.getText().toString();
                Integer i = Integer.parseInt(time);
                Intent intent = new Intent(getApplicationContext(), MyBroadCast.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);                                                 
                AlarmManager alarmManager = (AlarmManager) getSystemServiceALARM_SERVICE);
                alarmManager.set(alarmManager.RTC_WAKEUP, System.currentTimeMillis() +1 * 1000, pendingIntent);
                Toast.makeText(getApplicationContext(), "Alarm set in " + i +" secons", Toast.LENGTH_LONG).show();
            }
        });
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ss.broadcastexample.MainActivity">
<EditText    android:id="@+id/time"   
 android:layout_width="wrap_content"  
  android:layout_height="wrap_content"    
android:hint="Number of seconds"    
android:inputType="numberDecimal"/>
<Button    android:id="@+id/ok"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content"   
 android:text="Start Counter"/>\
</LinearLayout>
Create New MyBroadCast.java class 
package com.ss.broadcastexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;
/** * Created by bhall on 2/9/2018. */
public class MyBroadCast extends BroadcastReceiver {
     @Override    
public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Notify me after some time Your              time is up!!!!.", Toast.LENGTH_LONG).show();        // Vibrate the mobile phone       
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);       
vibrator.vibrate(4000);    }    
}
Test this Application   It will be Work Fine                                                                                  
                                                                                                                       

                                                                                                                           





Comments

  1. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to align Title at center of ActionBar in Android

How to Align Title At Center of Action Bar in Android                                                                                                                                                @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("DashBoard"); }   Activity  public void setTitle ( String title ){ getSupportActionBar (). setHomeButtonEnabled ( true ); getSupportActionBar (). setDisplayHomeAsUpEnabled ( true ); TextView textView = new TextView ( this ); textView . set...

SQLite Database With Android

Android provides several ways to store user and app data. SQLite is one way of storing user data. SQLite is a very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations. SQLite is a opensource  SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relation database features. In order to access this database you don't need to establish any kind of connections for it like JDBCODBC etc. In this tutorial I am taking an example of storing user Detail in SQLite database. I am using a table called UserMaster to store user detail. This table contains three columns  id (INT) , userid (VARCHAR) , username (VARCHAR) , password (VARCHAR) , address (VARCHAR) . Database- Package The main package is android.database.sqlite that contains the classes to mange your own database. In this Class we are creat...

Difference Between Pending Intent And Intent in Android

                       Normal Intent       Normal Intent will die as soon as the app being killed.    An Android Intent is an object carrying an intent, i.e a message from one Component to another     Component either inside or outside of the application.Intent can communicate message among     any of the three core Components of an application -- Activities, Services,and BroadcastReceivers.     Two types of Intent in Android   1. Explicit Intent.   2.Implicit Intent  Explicit Intent is an Intent which is used to Call the another component Explicitly in your application  Like :We are calling  Next activity on button click of First activity using Intent Example  // Explicit Intent by specifying its class name Intent i = new Intent ( this , TargetActivity . class ); i . putExtra ( "Key1" , "ABC" ); ...