Search code examples
androidbroadcastreceiversend

Send data from Broadcast receiver to MainActivity


I need to display status of connection on the screen. It seemed a simple task...

This is my receiver code below:

public class PowerConnectionReceiver extends BroadcastReceiver {

public PowerConnectionReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}
}

How can i display my STATE var on screen textView. Can anybody help with it? Thanks!


Solution

  • You need to register a Callback. Create an Interface in PowerConnectionReceiver like:

    public Interface NetworkStatusCallback {
        public void onStateChange(String state);
    }
    

    Now implement this Callback in your MainActivity like:

    public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback  {...}
    

    Create a reference of this Callback in PowerConnectionReceiver and declare it like:

    private NetworkStatusCallback mCallback;
    mCallBack = (NetworkStatusCallback)context;
    

    Now in onReceive(Context context, Intent intent) do this:

    @Override
    public void onReceive(Context context, Intent intent) {
        String state;
        if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
            state = "Charging";
            mCallback.onStateChange(state);
            Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    
        } else {
            intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
            state = "Not charging";
            mCallback.onStateChange(state);
            Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
        }
    }
    

    You will receive state in MainActivity