How to use interface to communicate between two activities

I would suggest to create a model class. Let me give you an example:

Model class:

public class CustomModel {

    public interface OnCustomStateListener {
        void stateChanged();
    }

    private static CustomModel mInstance;
    private OnCustomStateListener mListener;
    private boolean mState;

    private CustomModel() {}

    public static CustomModel getInstance() {
        if(mInstance == null) {
            mInstance = new CustomModel();
        }
        return mInstance;
    }

    public void setListener(OnCustomStateListener listener) {
        mListener = listener;
    }

    public void changeState(boolean state) {
        if(mListener != null) {
            mState = state;
            notifyStateChange();
        }
    }

    public boolean getState() {
        return mState;
    }

    private void notifyStateChange() {
        mListener.stateChanged();
    }
}

And here’s how you would use this:

// Imports
public class MainActivity extends Activity implements OnCustomStateListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomModel.getInstance().setListener(this);

        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "Current state: " + String.valueOf(modelState));

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    @Override
    public void stateChanged() {
        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "MainActivity says: Model state changed: " + 
            String.valueOf(modelState));
    }
}

Changing the member state in second activity:

// Imports
public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CustomModel.getInstance().changeState(true);
    }
}

LogCat output:

Current state: false

MainActivity says: Model state changed: true

Leave a Comment