Context registerComponentCallbacks

水一篇文章:

今天看Glide源碼時(shí)看到glide實(shí)現(xiàn)了 ComponentCallbacks 接口,注冊(cè)到了 Application 上面

這方法很少用啊,我就點(diǎn)開看了看

/**
 * Add a new {@link ComponentCallbacks} to the base application of the
 * Context, which will be called at the same times as the ComponentCallbacks
 * methods of activities and other components are called.  Note that you
 * <em>must</em> be sure to use {@link #unregisterComponentCallbacks} when
 * appropriate in the future; this will not be removed for you.
 *
 * @param callback The interface to call.  This can be either a
 * {@link ComponentCallbacks} or {@link ComponentCallbacks2} interface.
 */
public void registerComponentCallbacks(ComponentCallbacks callback) {
    getApplicationContext().registerComponentCallbacks(callback);
}

即是說用于自定義的安卓組件注冊(cè)來監(jiān)聽這個(gè) ComponentCallbacks回調(diào)

那么這個(gè)回調(diào)是啥呢?

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.content;

import android.annotation.NonNull;
import android.content.res.Configuration;

/**
 * The set of callback APIs that are common to all application components
 * ({@link android.app.Activity}, {@link android.app.Service},
 * {@link ContentProvider}, and {@link android.app.Application}).
 *
 * <p class="note"><strong>Note:</strong> You should also implement the {@link
 * ComponentCallbacks2} interface, which provides the {@link
 * ComponentCallbacks2#onTrimMemory} callback to help your app manage its memory usage more
 * effectively.</p>
 */
public interface ComponentCallbacks {
    /**
     * Called by the system when the device configuration changes while your
     * component is running.  Note that, unlike activities, other components
     * are never restarted when a configuration changes: they must always deal
     * with the results of the change, such as by re-retrieving resources.
     *
     * <p>At the time that this function has been called, your Resources
     * object will have been updated to return resource values matching the
     * new configuration.
     *
     * <p>For more information, read <a href="{@docRoot}guide/topics/resources/runtime-changes.html"
     * >Handling Runtime Changes</a>.
     *
     * @param newConfig The new device configuration.
     */
    void onConfigurationChanged(@NonNull Configuration newConfig);

    /**
     * This is called when the overall system is running low on memory, and
     * actively running processes should trim their memory usage.  While
     * the exact point at which this will be called is not defined, generally
     * it will happen when all background process have been killed.
     * That is, before reaching the point of killing processes hosting
     * service and foreground UI that we would like to avoid killing.
     *
     * <p>You should implement this method to release
     * any caches or other unnecessary resources you may be holding on to.
     * The system will perform a garbage collection for you after returning from this method.
     * <p>Preferably, you should implement {@link ComponentCallbacks2#onTrimMemory} from
     * {@link ComponentCallbacks2} to incrementally unload your resources based on various
     * levels of memory demands.  That API is available for API level 14 and higher, so you should
     * only use this {@link #onLowMemory} method as a fallback for older versions, which can be
     * treated the same as {@link ComponentCallbacks2#onTrimMemory} with the {@link
     * ComponentCallbacks2#TRIM_MEMORY_COMPLETE} level.</p>
     */
    void onLowMemory();
}

兩個(gè)方法,一個(gè)是 Configuration有變化,Activity在接收到Configuration變化時(shí)會(huì)銷毀重建(前提是沒在Manifest里面設(shè)置相應(yīng)的 android:configChanges)而組件是不會(huì)觸發(fā)類似的銷毀重建的,所以必須有一個(gè)地方來處理這些改變的值。

另一個(gè)是內(nèi)存不夠了,如果沒專門指定觸發(fā)時(shí)機(jī),那它會(huì)發(fā)生在所有的后臺(tái)進(jìn)程都被干掉的時(shí)候(在service和前臺(tái)UI被干掉之前);這個(gè)方法結(jié)束后系統(tǒng)會(huì)觸發(fā)GC。

另外注釋里有提到 ComponentCallbacks2 這個(gè)接口有 onTrimMemory 方法,它會(huì)根據(jù)不同的清理進(jìn)程釋放內(nèi)存的時(shí)機(jī)多次觸發(fā)。

/**
 * Called when the operating system has determined that it is a good
 * time for a process to trim unneeded memory from its process.  This will
 * happen for example when it goes in the background and there is not enough
 * memory to keep as many background processes running as desired.  You
 * should never compare to exact values of the level, since new intermediate
 * values may be added -- you will typically want to compare if the value
 * is greater or equal to a level you are interested in.
 *
 * <p>To retrieve the processes current trim level at any point, you can
 * use {@link android.app.ActivityManager#getMyMemoryState
 * ActivityManager.getMyMemoryState(RunningAppProcessInfo)}.
 *
 * @param level The context of the trim, giving a hint of the amount of
 * trimming the application may like to perform.
 */
void onTrimMemory(@TrimMemoryLevel int level);

ComponentCallbacks2 這個(gè)接口繼承了 ComponentCallbacks ,如果需要實(shí)現(xiàn) onTrimMemory這個(gè)方法就可以實(shí)現(xiàn)它

最后我們看看Glide實(shí)現(xiàn)這個(gè)接口是做什么:

Glide沒處理 configchange,只是在內(nèi)存不足時(shí)進(jìn)行了釋放內(nèi)存的操作

@Override
public void onTrimMemory(int level) {
  trimMemory(level);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
  // Do nothing.
}

@Override
public void onLowMemory() {
  clearMemory();
}

/**
 * Clears as much memory as possible.
 *
 * @see android.content.ComponentCallbacks#onLowMemory()
 * @see android.content.ComponentCallbacks2#onLowMemory()
 */
public void clearMemory() {
  // Engine asserts this anyway when removing resources, fail faster and consistently
  Util.assertMainThread();
  // memory cache needs to be cleared before bitmap pool to clear re-pooled Bitmaps too. See #687.
  memoryCache.clearMemory();
  bitmapPool.clearMemory();
  arrayPool.clearMemory();
}

/**
 * Clears some memory with the exact amount depending on the given level.
 *
 * @see android.content.ComponentCallbacks2#onTrimMemory(int)
 */
public void trimMemory(int level) {
  // Engine asserts this anyway when removing resources, fail faster and consistently
  Util.assertMainThread();
  // memory cache needs to be trimmed before bitmap pool to trim re-pooled Bitmaps too. See #687.
  memoryCache.trimMemory(level);
  bitmapPool.trimMemory(level);
  arrayPool.trimMemory(level);
} 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容