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