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...

Get Current location using FusedLocationProviderClient in Android

Hello to coders, Previously we have taught you  how you get current location using GPS/Network Provider . Then android has revealed  FusedLocationProviderClient  under  GoogleApi . FusedLocationProviderClient is for interacting with the location using fused location provider. ( NOTE :   To use this feature, GPS must be turned on your device. For manually ask the user to turn on GPS, please check  next article ) So let’s get started for the tutorial for getting the current location. First, add a dependency for location by play services: implementation 'com.google.android.gms:play-services-location:15.0.1' Then define FusedLocationProviderClient: private FusedLocationProviderClient mFusedLocationClient; private TextView txtLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_main ); this.txtLocation = (TextView) findViewById(R.id. txtLocat...

Get You Last known Location & Current Location using FusedLocationProviderClient

NOVEMBER 30, 2017 Get You Last known Location & Current Location using FusedLocationProviderClient        I would like to cover very basic and simple example of retreiving last known location & Current Location  using Fused location API.  I have written many example for fused location API in my previous posts but in this post i will show how to get retrieve the location  without implementing Google Api Client . All these magics happen after the release of version  11.0.0 of Google Play services SDK. FusedLocationProviderApi is Deprecated We have previously used following way to retrieve the last known location. mLastLocation  =  LocationServices. FusedLocationApi . getLastLocation ( mGoogleApiClient ) ; We no need to define LocationServices. FusedLocationApi  anymore. it is deprecated. It will be removed in the future release. Instead You can use LocationServi...