An overview of the

HarmonyOS is inevitably compared with Android. In the application development hierarchy, HarmonyOS ‘Ability is very similar to Android’s Activity positioning. Due to the large number of Ability categories and limited space, This article will briefly introduce the difference and connection between Page Ability and Activity.

define

  • Page Ability (” Page”) provides the Ability to interact with users. An application can be composed of multiple pages, and a Page can be composed of one or more AbilitySlice. AbilitySlice refers to the sum of a single Page of an application and its control logic.
  • Activity An entry point for users to interact with applications. An application can be composed of one or more activities, and an Activity can be composed of zero, one or more fragments. Fragments are part of the FragmentActivity behavior or interface.

Together:
  1. Both are interactive portals between users and applications.
  2. Can be composed of one or more applications.
The difference between:

1. The Ability:

public class Ability extends AbilityContext implements ILifecycle {
   public Ability(a) {
        throw new RuntimeException("Stub!"); }... }Copy the code

AbilitySlice:

public class AbilitySlice extends AbilityContext implements ILifecycle {
    public AbilitySlice(a) {
        throw new RuntimeException("Stub!"); }...public final Ability getAbility(a) {
        throw new RuntimeException("Stub!"); }}Copy the code

The parent class:

public abstract class Context {... }Copy the code
public interface Context {... }Copy the code

Both inherit from AbilityContext and implement the ILifecycle interface. On Android, Activity:

public class AppCompatActivity extends FragmentActivity implements AppCompatCallback.TaskStackBuilder.SupportParentable.ActionBarDrawerToggle.DelegateProvider {
        ...}
        
public class FragmentActivity extends ComponentActivity implements
        ActivityCompat.OnRequestPermissionsResultCallback.ActivityCompat.RequestPermissionsRequestCodeValidator {
        ...}

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner.ViewModelStoreOwner.HasDefaultViewModelProviderFactory.SavedStateRegistryOwner.OnBackPressedDispatcherOwner {
        ...}
        
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements
        LifecycleOwner.KeyEventDispatcher.Component {
        ...}

public class Activity extends ContextThemeWrapper implements Factory2.Callback.android.view.KeyEvent.Callback.OnCreateContextMenuListener.ComponentCallbacks2 {
        ..}
        
public class ContextThemeWrapper extends ContextWrapper {.. }public class ContextWrapper extends Context { ...}

public abstract class Context {... }Copy the code

Fragment:

public class Fragment implements ComponentCallbacks.OnCreateContextMenuListener.LifecycleOwner.ViewModelStoreOwner.HasDefaultViewModelProviderFactory.SavedStateRegistryOwner {... }Copy the code

On Android, an Activity is different from a Fragment, which is much lighter than an Activity. Appactivity has multiple parent classes, which are more sophisticated than Ability, but also much more complex.

2. Although a Page can be composed of one or more AbilitySlice, and an Activity can have zero, one or more fragments, the interface displays only one AbilitySlice by default when the Page enters the foreground. AlibitySlice is essential to a Page. AlibitySlice is more like a Page from Page to Page, with routes to each other, similar to an Activity. Fragments are a Fragment that Android introduced in Android 3.0 (API level 11) to support more dynamic and flexible interface design on large screens such as tablets. Because tablets’ screens are much bigger than phones’, there is more room to combine and swap interface components. Fragments are more like pagination, and can be displayed alongside one or more Fragment pages in addition to the Activity’s own page, providing a better user experience. A Fragment is a component of an Activity. AbilitySlice is the sum of a single Page and its control logic.

The life cycle

Ability Lifecycle:

public class Lifecycle {
    public Lifecycle(a) {
        throw new RuntimeException("Stub!");
    }

    public void addObserver(ILifecycleObserver observer) {
        throw new RuntimeException("Stub!");
    }

    public void removeObserver(ILifecycleObserver observer) {
        throw new RuntimeException("Stub!");
    }

    public Lifecycle.Event getLifecycleState(a) {
        throw new RuntimeException("Stub!");
    }

    public static enum Event {
        UNDEFINED,
        ON_START,
        ON_INACTIVE,
        ON_ACTIVE,
        ON_BACKGROUND,
        ON_FOREGROUND,
        ON_STOP;

        private Event(a) {}}}Copy the code

Activity lifecycle:

public abstract class Lifecycle {
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
    @MainThread
    @NonNull
    public abstract State getCurrentState(a);
    @SuppressWarnings("WeakerAccess")
    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }
    @SuppressWarnings("WeakerAccess")
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0; }}}Copy the code

Ability and Activity have roughly the same life cycle, both for flowcharts and source code.

Ability Activity
onStart() onCreate(),onStart()
onActive() onResume()
onInactive() onPause()
onBackground() onStop()
onForeground() onRestart()
onStop() onDestory()
Although some lifecycle names can correspond, the specific definition of each phase of the lifecycle varies greatly:

1. Create. OnStart () is triggered by HarmonyOS when the Page instance is first created. For a Page instance, this callback is triggered only once during its life cycle, and the Page will enter INACTIVE state after onStart() is called. The developer must override this method and configure AbilitySlice to be displayed by default here.

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(FooSlice.class.getName());
Copy the code

Android onCreate() when the system first creates an Activity. The Activity enters the created state after it is created. In the onCreate() method, you perform the basic application launch logic, which should only happen once during the Activity’s lifetime. Use to bind data to lists, correlate, instantiate some class-scope variables, or restore saved state.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // recovering the instance state
    if(savedInstanceState ! =null) {
        gameState = savedInstanceState.getString(GAME_STATE_KEY);
    }
    // set the user interface layout for this activity
    // the layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);
}
Copy the code

2. Visible. HarmonyOS Page calls onStart() and enters INACTIVE state. On Android, the system calls onStart() when an Activity enters the “Started” state. The onStart() call makes the Activity visible to the user because the application prepares the Activity for coming to the foreground and supporting interaction. In this case, it is visible but cannot interact with the user. The application initializes the maintenance interface code through this method. Regardless of the system, this state is accomplished very quickly, and then the interactive state is entered.

   @Override
    protected void onStart(a) {
        super.onStart();
    }
Copy the code

(3) interaction. HarmonyOS Page comes to the foreground when it is in INACTIVE state and the system calls onActive(). Page then enters the ACTIVE state, which indicates the interaction between the application and the user. The Page will remain in this state unless some sort of event occurs that causes the Page to lose focus, such as the user clicking the back key or navigating to another Page.

    @Override
    protected void onActive(a) {
        super.onActive();
    }

Copy the code

The Android Activity comes to the foreground when it enters the “Resumed” state and the system calls the onResume() callback. At this point, the lifecycle component can enable any functionality that needs to run while the component is visible and in the foreground. This is the state in which the app interacts with the user, and the app stays that way until something happens that takes the focus away from the app. Such events include receiving an incoming call, the user navigating to another Activity, or the device screen shutting down.

    @Override
    protected void onResume(a) {
        super.onResume();
    }
Copy the code

4. Out of focus. When HarmonyOS Page loses focus, onInactive() is called and the Page enters INACTIVE state. This callback allows developers to implement the appropriate behavior that a Page should behave when it loses focus. After that, the Page may return to the ACTIVE state, and the onActive() callback will be invoked again. Therefore, developers usually need to implement onActive() and onInactive() in pairs, and in onActive() take the resources released in onInactive().

    @Override
    protected void onInactive(a) {
        super.onInactive();
    }

Copy the code

The first sign that an Android user is leaving an Activity (although this does not always mean the Activity will be destroyed) calls onPause(); This method indicates that the Activity is no longer in the foreground (although it is still visible when the user is in multi-window mode). Use onPause() to pause or adjust actions that should not continue (or should continue sparingly) while the Activity is in the “paused” state, as well as actions that you want to resume soon. When the paused state is entered, all life-cycle-aware components associated with the Activity lifecycle receive the ON_PAUSE event. At this point, the lifecycle component can stop any functionality that does not need to run when the component is not in the foreground. If the Activity resumes in time, the onResume() callback is called again. If the Activity returns from the “Paused” state to the “Resumed” state, the system lets the Activity instance continue to reside in memory and recalls it when the system calls onResume(). In this case, you do not need to reinitialize components created during any callback method that causes the Activity to enter the “Recovered” state.


    @Override
    protected void onPause(a) {
        super.onPause();
    }

Copy the code

Regardless of the system, this state is not interactive and may still be visible. 5. Not visible. The HarmonyOS Page is no longer visible to users, and the system calls this callback to notify the developer that the user has released the resource. After that, the Page is in the BACKGROUND state. This callback should either free resources that are useless when the Page is not visible, or perform time-consuming state saving operations in this callback.

    @Override
    protected void onBackground(a) {
        super.onBackground();
    }

Copy the code

If the Android Activity is no longer visible to the user, it has entered the “Stopped” state, so the system calls the onStop() callback. This can happen, for example, when a newly launched Activity covers the entire screen. The system can also call onStop() if the Activity has finished running and is about to be terminated. When an Activity enters the stopped state, all life-cycle-aware components associated with the Activity lifecycle receive ON_STOP events. At this point, the lifecycle component can stop any functionality that does not need to run when the component is not displayed on the screen. In the onStop() method, the application should release or adjust unwanted resources when the application is not visible to the user.

 @Override
    protected void onStart(a) {
        super.onStart();
    }
Copy the code

6. Rebirth. HarmonyOS ‘BACKGROUND Page still resides in memory. When returned to the foreground (for example, when the user navigates to the Page again), the onForeground() callback is called to notify the developer, and the Page’s life cycle state goes back to INACTIVE. The developer should reapply for the resources released in onBackground() in this callback, and eventually the Page’s lifecycle state will return further to the ACTIVE state, and the developer user will be notified via the onActive() callback.

   @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

Copy the code

The Android user returns quickly. If the Activity is not killed, onRestart() is called, then onStart() is called to enter the visible state, and onResume() is called to enter the interactive state, and the user performs related operations.


    @Override
    protected void onRestart(a) {
        super.onRestart();
    }
Copy the code

7. Destroyed. When HarmonyOS is about to destroy a Page, onStop() is triggered to notify the user of the release of system resources. All instantiated AbilitySlice will be destroyed in linkage, not just AbilitySlice in the foreground.

  @Override
    protected void onStop(a) {
        super.onStop();
    }
Copy the code

The system calls onDestroy() before Android destroys its Ativity. At this point, the lifecycle component can clean up any data needed to free up any resources before the Activity is destroyed.

    @Override
    protected void onDestroy(a) {
        super.onDestroy();
    }
Copy the code

Little different

1. Configuration file. Ability related registrations need to be registered in config.json.

{
    "module": {..."abilities": [{..."type": "page". }]... }... }Copy the code

The Activity needs to be registered in androidmanifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="...">... <application ... >... </application> </manifest>Copy the code

2. Add layout. Ability:

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    Load the XML layout as the root layout
    super.setUIContent(ResourceTable.Layout_first_layout);
 }
Copy the code

The Activity:

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_main;) ; }Copy the code

instructions

  • The HarmonyOS related material in this article comes from the HarmonyOS Developer documentation.
  • The Android related materials in this article are taken from the Android Developer development guide.
  • For infringement or error, please send an email to [email protected].