Thursday, 24 December 2015

Android - Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action

There are following two important steps to make BroadcastReceiver works for the system broadcasted intents −
·        Creating the Broadcast Receiver.
·        Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents
actvity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
   
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textAppearance="?android:attr/textAppearanceLarge"
       
android:text="Welcome to Broadcast Receiver"
       
android:id="@+id/textView"
       
android:layout_gravity="center_horizontal" />
</
LinearLayout>

MainActvity.Java
package com.sra.ani.broadcastreceiver;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;


public class MainActivity extends AppCompatActivity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.
toolbar);
        setSupportActionBar(toolbar);
    registerReceiver(
new MyBroadcast(),new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
}

MyBroadcast.Java
package com.sra.ani.broadcastreceiver;

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

/**
 * Created by Sra on 12/24/15.
 */
public class MyBroadcast extends BroadcastReceiver {
   
@Override
   
public void onReceive(Context context, Intent intent) {
       
int bstatus=intent.getIntExtra("level",0);
        Toast.makeText(context,
"Your Battery Status is : "+bstatus, Toast.LENGTH_SHORT).show();
    }
}

Output




No comments:

Post a Comment