Monday, 4 February 2019

How to use "Listener" inside Broadcast example

If we wants to update anyUI base using listener inside  Broadcast OnReceive() method than we have to do the following:-

1. Like there is a text_box in MainActivity.java where we have to set text if power connected to the phone .
2. create Listener like following
public interface ListenerBroadcast {
    void setDataFromBroadcast(String broadcastData);
}
2. Open MainActivity and take a text_box inside xml code will be like following:-
activity_main:-
Implement ListenerBroadcast to the MainActivity and override the method code will be :-
@Override
public void setDataFromBroadcast(String broadcastData) {
    dataOfBroadcast.setText("Broadcast Data = "+ broadcastData);
}
dataOfBroadcast is obj of Textview.
<TextView
    android:id="@+id/dataOfBroadcast"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
inside OnCreate():-
MyBroadcast.setDataFromBroadcast(this);
3. Add MyBroadcast class and inside onReceive() code will be following:-

public class MyBroadcast extends BroadcastReceiver {
    private static ListenerBroadcast listenerBroadcast;
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Power connected",Toast.LENGTH_LONG).show();
        if(listenerBroadcast != null ) {
            listenerBroadcast.setDataFromBroadcast("ACTION_POWER_CONNECTED");
        }
    }
    public static void setDataFromBroadcast(ListenerBroadcast listener){
        listenerBroadcast = listener;

    }
}
4. Add Broadcast to the Manifest.xml file 
<receiver android:name=".MyBroadcast">
    <intent-filter >
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    </intent-filter>
</receiver>

No comments:

Post a Comment