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 . setText ( title ); textView . setTextSize ( 20 ); textView . setTypeface ( null , Typeface . BOLD ); textView . setLayoutParams ( new LinearLayout . LayoutParams ( LinearLayout . LayoutParams . FILL_PARENT , LinearLayout . LayoutParams . WRAP_CONTENT )); textView . setGravity ( Gravity . CENTER ); textView . setTextColor ( getResources (). ge

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" ); i . putExtra ( "Key2" , "123" ); // Starts TargetActivity startActivity ( i );  Implicit Intent Intent

Expected a key while parsing a block mapping (Flutter)

Flutter makes use of the Dart packaging system, pub. Via your applications  pubspec.yam l file (or simple pubspec), you can pull down packages from the flutter ecosystem, or the broader dart community. Anyway, i need to add some images to my flutter application, and so had to add an assets section to the pubspec .the default Android Studio generated apps pubspec has a lot of commented out code with explainations about what is going on, e.g # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. So I uncommented these lines # assest : - - - #  -  images/a_dot_ham.jpeg with the idea from these comment.  that i would just edit it to suit my particular needs. Once you have edited your  pubspec, you need to click on the "Get dependencies"