ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Android Architecture
    Mobile/Android 2020. 6. 2. 15:39

    1. Architecture

    1.1 Android Activity Lifecycle

    1.2 State Lifecycle

    2. Component

    Component Description
    Activities

    They dictate the UI and handle the user interaction with the smartphone screen.

    Services

    They handle background processing associated with an application.

    Broadcast Receivers

    They handle communication between Android OS and applications.

    Content Providers

    They handle data and database management issues.

    2.1 Activity

    An activity represents a single screen with a user interface, in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.

    2.1.1 Implementation

    public class MainActivity extends Activity {
    }

    2.2 Service

    A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

    2.2.1 Implementation

    public class MyService extends Service {
    }

    2.3 BroadcastReceiver

    Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is a broadcast receiver who will intercept this communication and will initiate appropriate action.

    A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object.

    2.3.1 Implementation

    public class MyReceiver  extends  BroadcastReceiver {
       public void onReceive(context,intent){}
    }

    2.4 ContentProvider

    A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database, or somewhere else entirely.

    A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.

    2.4.1 Implementation

    public class MyContentProvider extends  ContentProvider {
       public void onCreate(){}
    }

    2.5 Additional Components

    Component Description
    Fragments

    Represents a portion of the user interface in an Activity.

    Views

    UI elements that are drawn on-screen including buttons, lists forms, etc.

    Layouts

    View hierarchies that control screen format and appearance of the views.

    Intents

    Messages wiring components together.

    Resources

    External elements, such as strings, constants, and drawable pictures.

    Manifest

    Configuration file for the application.

    3. Context

    Android application is using java, but not like java that you can create a class and main() function, then able to run. Android is based on components including Activity, Service, Content Provider, and Broadcast receiver. You are not able to create a new component simply by using 'new' since all of these components have their own context. Activity extends from Context, Service, and Application also extends from Context.

    Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

    3.1 How many Context in an Application?

    From above, we can conclude that Number(Context)=Activity+Service+1(Application). For other components like Context Provider, Broadcast Receiver which is not a subclass of Context. So they are not counted, but we need to pass context objects to them when creating a new one.

    3.2 What Context can do?

    Context is powerful, but it still has some restrictions. Since context is implemented by ContextImpl, so in most situations we can use activity, service, and application context in common. However, in some situation like start an Activity or pop up a dialog, it must use Activity context since a new Activity is based on another Activity to form a stack, also a popup dialog needs to show on top of Activity except some system alert dialog.

    • If we use ApplicationContext to start an Activity with standard launch mode, it will throw exception "android.util.AndroidRuntimeException: Calling startActivity from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?" This exception is because the non Activity context does not have the back stack. So from service and application is only to use FLAG_ACTIVITY_NEW_TASK (this activity will become the start of a new task on this history stack.) to start an Activity, which is not recommended.
    • It is able to inflate the layout, but will only apply the default theme of the android system, those custom theme will not able to apply since only Activity extends ContextThemeWrapper class.

    3.3 Where to use

    Where to use Application Activity Service
    Show a Dialog No Yes No
    Start an Activity Not Recommended Yes Not Recommended
    Layout Inflation Not Recommended Yes Not Recommended
    Start a Service Yes Yes Yes
    Send a Broadcast Yes Yes Yes
    Register Broadcast Receiver Yes Yes Yes
    Load Resource Values Yes Yes Yes

    3.4 Ways to get Context

    • view.getContext() it's the activity context which the view is hosted
    • Activity.getApplicationContext() get the current application context, when we need context, this global context needs to be considered at first.
    • Activity.this when some UI controllers need context or start an Activity. Toast can use ApplicationContext.

    3.5 Difference between getApplication() and getApplicationContext()

    Actually both functions return application objects since the application itself is a context. So why android provide two functions? The reason is that getApplication() is only able to be used in Activity and Service. In other components like BroadcastReceiver is only able to use getApplicationContext() to get application object.

    @Override
    public Context getApplicationContext() {
            return (mPackageInfo != null) ?
                    mPackageInfo.getApplication() : mMainThread.getApplication();
    }

    3.6 Improper use of context can easily cause a memory leak

    3.6.1 Case 1

    public class Singleton{
        private static Singleton instance;
        private Context mContext;
        
        private Singleton(){};
        
        public static Singleton getInstance(Context context){
            if(instance==null){
                synchronized(Singleton.class){
                    if(instance==null){
                        instance = new Singleton();
                        mContext = context;
                    }
                }
            }
            return instance;
        }
    }

    Since Singleton will live a long time in the application which causes the context which is held by it will not able to be GC.

    3.6.2 Case 2

    public class MainActivity extends Activity {
        private static ImageView mImageView;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ...
            mImageView = (ImageView)findViewById(R.id.imageId);
    }

    Since mImageView is static, and the current context which is Activity.this is referenced by imageview, so the whole Activity is leaked.

    4. Intent

    The intent is the medium to pass between components such as activities, content providers, broadcast receivers, services, etc.

    4.1 Implicit Intent

    Implicit Intent doesn’t specify the component in the app. In such a case, intent provides information on available components provided by the system that is to be invoked.

    4.1.1 Example

    A button on click of which you will redirect to a web page. If your Device has multiple browsers then option popup (bottom sheet) will open and show them all.

    4.2 Explicit Intent

    Explicit intent specifies the component in an application, that is which class to be invoked. You can pass the information from one activity to another using an explicit intent.

    4.2.1 Example

    On click, the button goes to another Activity. As a definition, we know about the target component.

    4.3 Cases

    • Start the service
    • Launch an activity
    • Display a web page
    • Broadcast a message
    • Dial a phone call.
    • Map GEO location

    5. Fragments

    A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity.

    • A fragment has its own layout and its own behavior with its own life cycle callbacks.
    • You can add or remove fragments in an activity while the activity is running.
    • You can combine multiple fragments in a single activity to build a multi-pane UI.
    • A fragment can be used in multiple activities.
    • Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped.
    • A fragment can implement behavior that has no user interface component.
    • Fragments were added to the Android API in Honeycomb version of Android which API version 11.

    You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.

    Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide the device screen and control different parts separately. But with the introduction of the fragment, we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single activity but each activity can comprise multiple fragments that will have their own layout, events, and complete life cycle.

    The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article.

    5.1 Fragment Lifecycle

    5.2 Types of Fragments

    Types Desciption
    Single frame fragments Single frame fragments are using for handheld devices like mobiles, here we can show only one fragment as a view.
    List fragment fragments having special list view is called as list fragment
    Fragments transaction Using a fragment transaction. we can move one fragment to another fragment.

    5.3 How to use Fragments

    1. First of all, decide how many fragments you want to use in an activity. For example, let's we want to use two fragments to handle landscape and portrait modes of the device.
    2. Next based on the number of fragments, create classes that will extend the Fragment class. The Fragment class has the above-mentioned callback functions. You can override any of the functions based on your requirements.
    3. Corresponding to each fragment, you will need to create layout files in the XML file. These files will have the layout for the defined fragments.
    4. Finally, modify the activity file to define the actual logic of replacing fragments based on your requirement.

    5.4 Fragment Methods

    Method Description
    onAttach() The fragment instance is associated with an activity instance. The fragment and the activity are not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.
    onCreate() The system calls this method when creating the fragment. You should initialize the essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
    onCreateView() The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
    onActivityCreated() The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method, you can instantiate objects which require a Context object
    onStart() The onStart() method is called once the fragment gets visible.
    onResume() Fragment becomes active.
    onPause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
    onStop() Fragment going to be stopped by calling onStop()
    onDestroyView() Fragment view will destroy after calling this method
    onDestroy() onDestroy() called to do a final clean up of the fragment's state but Not guaranteed to be called by the Android platform.

    6. Reference

    https://www.oreilly.com/library/view/android-cookbook-2nd/9781449374471/ch01.html

    https://tutorial.eyehunts.com/android/types-implicit-intent-explicit-intent-android/

    https://developer.android.com/guide/platform

    https://www.tutorialspoint.com/android/android_architecture.htm

    https://ericyang505.github.io/android/Context.html

    https://www.tutorialspoint.com/android/android_intents_filters.htm

    https://www.tutorialspoint.com/android/android_fragments.htm

    http://thebirdsarecomingcloseyourwindows.blogspot.com/2013/05/android-components.html

    https://sites.google.com/site/andoruo/2012nian-nian-du-fa-zheng-da-xue-qing-bao-ke-xue-buyubikitasukonpyutingu/android-2-intent?tmpl=%2Fsystem%2Fapp%2Ftemplates%2Fprint%2F&showPrintDialog=1

    'Mobile > Android' 카테고리의 다른 글

    UI Thread  (0) 2020.05.26
    Garbage Collector, Memory Leaks, and Thread Termination in Android  (0) 2020.05.26
    Android Processes and Threads  (0) 2020.05.26

    댓글

Designed by Tistory.