Custom Broadcast

This example will show how you can send and receive the broadcast from your application.

Steps :
1) For sending the broadcast from your application you can use sendBroadcast() method.
2) To receive that broadcast you need to add the receiver to the manifest file.
3) Create the broadcast receiver that will handle the broadcast send by your application and do exactly what you want.

1) Sending broadcast from your application:-  
Main.java

public class MainActivity extends AppCompatActivity {

     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent i = new Intent();
        i.setAction("Mybrodcast"); 
            //You can set any action name instead of Mybrodcast suitable to your application
        i.putExtra("Message","This is just example to show you how to 
                      send brodcast from your application." );
        sendBroadcast(i);
    }
}

2) Register this broadcast to manifest.xml:-
manifest.xml

<manifest package="custombrodcastreceivernotfy.example.com.custombrodcastreceivernotfy">
    <application>
    <receiver android:name=".brodcastreceive">
        <intent-filter><action android:name="Mybrodcast"></action> </intent-filter>
    </receiver>
    </application>
</manifest>

3) Create the broadcast receiver to perform some task when broadcast received.
brodcastreceive.java

public class brodcastreceive extends BroadcastReceiver {


@Override    
public void onReceive(Context context, Intent intent) {
int i=1;

if(intent.getAction().equals("Mybrodcast")) {
Toast.makeText(context,"Hello",Toast.LENGTH_SHORT).show();

NotificationManager  notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

Notification.Builder builder = new Notification.Builder(context);
builder.setContentIntent(contentIntent).setSmallIcon(android.R.drawable.ic_dialog_email).setContentTitle("Message").setContentText(intent.getStringExtra("Message"));
Notification notify=builder.build();
notificationManager.notify(i,notify);
i++;
        }
    }




Output




    


Comments