Skip to content

Creating your first unit

Ognyan Bankov edited this page Oct 25, 2016 · 5 revisions

Creating your first unit

There is a minimalistic example of a Forge application forge-admin-examples-basic. Please download it and use it as a skeleton for your next experiments.

We will create a unit called simple. First we have to create a directory for it under units, i.e. units/simple.

Creating the resident component

When starting with a new unit next thing is to create your resident component. Following the Forge code conventions we will prefix the name of the component with Res to ResSimple. When you intent to use unit tests it is recommended to name ResSimple the interface that defines the resident's interface, and name ResSimpleImpl the actual implementation. For the sake of simplicity we will just create the implementation. We can do it like this:

class ResSimple extends ResidentComponent {
}

but since ResidentComponent is an interface we will be forced to implement all its methods, so there is an easier way - use ResidentComponentAdapter which provides empty implementations for the lifecycle callbacks:

class ResSimple extends ResidentComponentAdapter {

Please note that the access level is default/package.

Creating the unit activity

In the skeleton project there is a class UnitBaseActivity which we will use as a base for our unit activity. UnitBaseActivity provides implementation of the UnitActivity interface.

public class ActSimple extends UnitBaseActivity<ResSimple> {

Note that we provide ResSimple as the generic type. That way we tell the framework, that this activity will work with that resident component and when we call getResident() we will get object of type ResSimple.

Now we have to implement createResidentComponent() method in order to instantiate our resident component.

❗ Please note that createResidentComponent() is intended to be called only by the unit manager and not by you.

public class ActSimple extends UnitBaseActivity<ResSimple> {
    @NonNull
    @Override
    public ResidentComponent createResidentComponent() {
        return new ResSimple();
    }
}

Running your new unit

Now you have to add a button to ActMain which starts your new unit by starting it's activity (the usual way):

Intent intent = new Intent(ActMain.this, ActSimple.class);
startActivity(intent);

Congratulations, you have just created your first forge unit! 🎉🎉🎉

What's next?

Next tutorial is More realistic example