Chuyển đến nội dung chính

Understanding the Android Application Class

Overview

The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.

This class is primarily used for initialization of global state before the first Activity is displayed. Note that custom Application objects should be used carefully and are often not needed at all.

Custom Application Classes

In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class:
  • Specialized tasks that need to run before the creation of your first activity
  • Global initialization that needs to be shared across all components (crash reporting, persistence)
  • Static methods for easy access to static immutable data such as a shared network client object
Note that you should never store mutable shared data inside the Application object since that data might disappear or become invalid at any time. Instead, store any mutable shared data using persistence strategies such as files, SharedPreferences or SQLite.

Defining Your Application Class

If we do want a custom application class, we start by creating a new class which extends android.app.Application as follows:
Java:
import android.app.Application;

public class MyCustomApplication extends Application {
        // Called when the application is starting, before any other application objects have been created.
        // Overriding this method is totally optional!
 @Override
 public void onCreate() {
     super.onCreate();
            // Required initialization logic here!
 }

        // Called by the system when the device configuration changes while your component is running.
        // Overriding this method is totally optional!
 @Override
 public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
 }

        // This is called when the overall system is running low on memory, 
        // and would like actively running processes to tighten their belts.
        // Overriding this method is totally optional!
 @Override
 public void onLowMemory() {
     super.onLowMemory();
 }
}
Kotlin:
import android.app.Application

class MyCustomApplication : Application() {
        // Called when the application is starting, before any other application objects have been created.
        // Overriding this method is totally optional!
 override fun onCreate() {
     super.onCreate()
            // Required initialization logic here!
 }

        // Called by the system when the device configuration changes while your component is running.
        // Overriding this method is totally optional!
 override fun onConfigurationChanged ( newConfig : Configuration ) {
     super.onConfigurationChanged(newConfig)
 }

        // This is called when the overall system is running low on memory, 
        // and would like actively running processes to tighten their belts.
        // Overriding this method is totally optional!
 override fun onLowMemory() {
     super.onLowMemory()
 }
}
And specify the android:name property in the the <application> node in AndroidManifest.xml:
<application 
   android:name=".MyCustomApplication"
   android:icon="@drawable/icon" 
   android:label="@string/app_name" 
   ...>
That's all you should need to get started with your custom application.

Limitations and Warnings

There is always data and information that is needed in many places within your app. This might be a session token, the result of an expensive computation, etc. It might be tempting to use the application instance in order to avoid the overhead of passing objects between activities or keeping those in persistent storage.
However, you should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.
So how should we store shared application data? We should store shared data in one of the following ways:
Bottom Line: Storing data in the Application object is error-prone and can crash your app. Prefer storing your global data on disk if it is really needed later or explicitly pass to your activity in the intent’s extras.

Resources

Nhận xét

Bài đăng phổ biến từ blog này

NHỮNG WIDGET THƯỜNG DÙNG TRONG FLUTTER

 https://baoflutter.com/nhung-widget-thuong-dung-trong-flutter/ Trong bài viết trước về  cách xây dựng màn hình ứng dụng Flutter , các bạn biết rằng các màn hình ứng dụng được tạo ra bởi các widget ghép lại với nhau. Vì vậy việc hiểu và sử dụng các Widget là rất quan trọng. Vì vậy trong bài viết này, tôi sẽ giới thiệu cho các bạn về những widget quan trọng trong Flutter. Hầu hết các Widget đều có các phần sau đây: + Đặc tính của Widget như : color, theme, height, weight, decoration, onTap, onPressed + Liên kết với các Widget khác với từ khoá: child, children, home hoặc body Ví dụ : 1 2 3 4 5 6 Container ( color : Colors . blue , height : 300 , weight : 300 , child : Text ( "Widget con" ) , ) Khi làm một số App cơ bản, bạn sẽ nắm chắc được cách sử dụng các Widget hay dùng. MaterialApp – Là widget rất liện lợi, cung cấp các widget cho việc xây dựng ứng dụng sử dụng thư viện Material Design UI của google. – Widget này được sử dụng trong hàm build đầu tiên của hầu hết các ứn...

Các bước cơ bản sử dụng Retrofit để thao tác với API và MVP

 Cài đặt  Retrofit //Retrofit implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' Cài đặt Gson implementation 'com.google.code.gson:gson:2.8.9' Cài thư viện Okhttp implementation 'com.squareup.okhttp3:okhttp:3.12.0' Sử dụng Gson ở trong project: 1. Tạo class App import android.app.Application ; import com.google.gson.Gson ; public class App extends Application { private static App mSelf ; private Gson mGSon ; public static App self () { return mSelf ; } @Override public void onCreate () { super .onCreate() ; mSelf = this; mGSon = new Gson() ; } public Gson getGSon () { return mGSon ; } } 2. Chỉnh file AndroidManifest: <? xml version ="1.0" encoding ="utf-8" ?> <manifest xmlns: android ="http://schemas.android.com/apk/res/android" xmlns: tools ="http://schemas.android....

Cấu trúc cơ bản layout trong Flutter