徹底理解Toast原理和解決小米MIUI系統上沒法彈Toast的問題


1、Toast的基本使用

  Toast在Android中屬於系統消息通知,用來提示用戶完成了什么操作、或者給用戶一個必要的提醒。Toast的官方定義是這樣的:

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive.

  它僅僅用作一個簡單的反饋機制。使用也比較簡單:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

  一般情況下,我們傳入一個String就基本上滿足大多數的需求。但要想自定義一個View,然后通過Toast進行顯示,也僅僅多了設置View的操作。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>

  我們把這個文件命名為toast_layout.xml,然后在代碼中加載它。

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

  其實就是這么簡單。

2、Toast原理解剖

  但現實是,產品需求說你給我控制Toast顯示的時間。咋一看好像也不難嘛。

  不是有個setDuration方法么?當你翻看源碼的時候,你會發現它的描述參數只有以下兩種:

LENGTH_SHORT
LENGTH_LONG

  這兩個常量對應着2秒和3.5秒,你傳個其它數字進入,效果並不是你所預料。其實這兩個常量僅僅是個flag,並不是我們想的多少秒。官方API文檔告訴我們:

This time could be user-definable.

  但,它又不提供一個公開的方法讓你設置。抓狂!先看一下Toast的顯示和隱藏在代碼層面做了什么事情。

/**
 * Show the view for the specified duration.
 */
public void show() {
    if (mNextView == null) {
        throw new RuntimeException("setView must have been called");
    }

    INotificationManager service = getService();
    String pkg = mContext.getOpPackageName();
    TN tn = mTN;
    tn.mNextView = mNextView;

    try {
        service.enqueueToast(pkg, tn, mDuration);
    } catch (RemoteException e) {
        // Empty
    }
}
/**
 * Close the view if it's showing, or don't show it if it isn't showing yet.
 * You do not normally have to call this.  Normally view will disappear on its own
 * after the appropriate duration.
 */
public void cancel() {
    mTN.hide();

    try {
        getService().cancelToast(mContext.getPackageName(), mTN);
    } catch (RemoteException e) {
        // Empty
    }
}

  理解這兩個方法,需要深挖getService()到底調用了那個類做enqueueToast的操作?TN類是干什么的?繼續跟蹤代碼。

static private INotificationManager getService() {
    if (sService != null) {
        return sService;
    }
    sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
    return sService;
}

  看到Stub.asInterface,我們知道這是利用Binder進行跨進程調用了。而TN類就是遵循AIDL的實現。

private static class TN extends ITransientNotification.Stub

  TN類內部使用Handler機制:post一個mShow和mHide:

final Runnable mShow = new Runnable() {
        @Override
        public void run() {
            handleShow();
        }
    };

final Runnable mHide = new Runnable() {
    @Override
    public void run() {
        handleHide();
        // Don't do this in handleHide() because it is also invoked by handleShow()
        mNextView = null;
    }
};

  再來看handleShow()方法的實現:

public void handleShow() {
        if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView
                + " mNextView=" + mNextView);
        if (mView != mNextView) {
            // remove the old view if necessary
            handleHide();
            mView = mNextView;
            Context context = mView.getContext().getApplicationContext();
            String packageName = mView.getContext().getOpPackageName();
            if (context == null) {
                context = mView.getContext();
            }
            mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
            // We can resolve the Gravity here by using the Locale for getting
            // the layout direction
            final Configuration config = mView.getContext().getResources().getConfiguration();
            final int gravity = Gravity.getAbsoluteGravity(mGravity, config.getLayoutDirection());
            mParams.gravity = gravity;
            if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
                mParams.horizontalWeight = 1.0f;
            }
            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
                mParams.verticalWeight = 1.0f;
            }
            mParams.x = mX;
            mParams.y = mY;
            mParams.verticalMargin = mVerticalMargin;
            mParams.horizontalMargin = mHorizontalMargin;
            mParams.packageName = packageName;
            if (mView.getParent() != null) {
                if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
                mWM.removeView(mView);
            }
            if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);
            mWM.addView(mView, mParams);
            trySendAccessibilityEvent();
        }
    }

  大概意思就是通過WindowManager的addView方法實現Toast的顯示。其中trySendAccessibilityEvent()方法會把當前的類名、應用的包名通過AccessibilityManager來做進一步的分發,以供后續的處理。

private void trySendAccessibilityEvent() {
        AccessibilityManager accessibilityManager =
                AccessibilityManager.getInstance(mView.getContext());
        if (!accessibilityManager.isEnabled()) {
            return;
        }
        // treat toasts as notifications since they are used to
        // announce a transient piece of information to the user
        AccessibilityEvent event = AccessibilityEvent.obtain(
                    AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
            event.setClassName(getClass().getName());
            event.setPackageName(mView.getContext().getPackageName());
        mView.dispatchPopulateAccessibilityEvent(event);
        accessibilityManager.sendAccessibilityEvent(event);
    }

  先回到前面的enqueueToast方法,看它做了什么事情。前面的INotificationManager service = getService()返回的就是NotificationManagerService,所以enqueueToast方法的最終實現在NotificationManagerService類中。

@Override
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
    if (DBG) {
        Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback
                + " duration=" + duration);
    }

    if (pkg == null || callback == null) {
        Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
        return ;
    }

    final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));

    if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
        if (!isSystemToast) {
            Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
            return;
        }
    }

    synchronized (mToastQueue) {
        int callingPid = Binder.getCallingPid();
        long callingId = Binder.clearCallingIdentity();
        try {
            ToastRecord record;
            int index = indexOfToastLocked(pkg, callback);
            // If it's already in the queue, we update it in place, we don't
            // move it to the end of the queue.
            if (index >= 0) {
                record = mToastQueue.get(index);
                record.update(duration);
            } else {
                // Limit the number of toasts that any given package except the android
                // package can enqueue.  Prevents DOS attacks and deals with leaks.
                if (!isSystemToast) {
                    int count = 0;
                    final int N = mToastQueue.size();
                    for (int i=0; i<N; i++) {
                         final ToastRecord r = mToastQueue.get(i);
                         if (r.pkg.equals(pkg)) {
                             count++;
                             if (count >= MAX_PACKAGE_NOTIFICATIONS) {
                                 Slog.e(TAG, "Package has already posted " + count
                                        + " toasts. Not showing more. Package=" + pkg);
                                 return;
                             }
                         }
                    }
                }

                record = new ToastRecord(callingPid, pkg, callback, duration);
                mToastQueue.add(record);
                index = mToastQueue.size() - 1;
                keepProcessAliveLocked(callingPid);
            }
            // If it's at index 0, it's the current toast.  It doesn't matter if it's
            // new or just been updated.  Call back and tell it to show itself.
            // If the callback fails, this will remove it from the list, so don't
            // assume that it's valid after this.
            if (index == 0) {
                showNextToastLocked();
            }
        } finally {
            Binder.restoreCallingIdentity(callingId);
        }
    }
}
static final int MAX_PACKAGE_NOTIFICATIONS = 50;
static final int LONG_DELAY = 3500; // 3.5 seconds
static final int SHORT_DELAY = 2000; // 2 seconds

  這段代碼主要做了以下幾件事情:

  • 獲取當前進程的Id。
  • 查看這個Toast是否在隊列中,有的話直接返回,並更新顯示時間。
  • 如果是非系統的Toast(通過應用包名進行判斷),且Toast的總數大於等於50,不再把新的Toast放入隊列。
  • 最后通過keepProcessAliveLocked(callingPid)方法來設置對應的進程為前台進程,保證不被銷毀。
  • 如果index = 0,說明Toast就處於隊列的頭部,直接進行顯示。
  • 我們在NotificationManagerService類中確認了前面提到的LENGTH_SHORT和LENGTH_LONG的顯示時長。

  關於上述的第四點,我們通過Toast類型的定義來印證代碼:

/**
 * Window type: transient notifications.
 * In multiuser systems shows only on the owning user's window.
 */
public static final int TYPE_TOAST              = FIRST_SYSTEM_WINDOW+5;

  所以一旦應用被銷毀,它對應的Toast也將不會再顯示:shows only on the owning user's window. 再來看這個keepProcessAliveLocked方法:

// lock on mToastQueue
void keepProcessAliveLocked(int pid)
{
    int toastCount = 0; // toasts from this pid
    ArrayList<ToastRecord> list = mToastQueue;
    int N = list.size();
    for (int i=0; i<N; i++) {
        ToastRecord r = list.get(i);
        if (r.pid == pid) {
            toastCount++;
        }
    }
    try {
        mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
    } catch (RemoteException e) {
        // Shouldn't happen.
    }
}

  其中mAm是一個ActivityManagerService實例,所以調用最終進入到ActivityManagerService的setProcessForeground方法進行再次處理。下面我用一張序列圖展示整個調用流程:

  其中第八步的scheduleTimeoutLocked()實質上就是利用Handler延時發送一個Message,回調TN類的hide()方法,最終通過WindowManager的removeView()來隱藏之前顯示的Toast。

private void scheduleTimeoutLocked(ToastRecord r)
    {
        mHandler.removeCallbacksAndMessages(r);
        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
        long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
        mHandler.sendMessageDelayed(m, delay);
    }

  至此,Toast的顯示和隱藏已經分析完畢。原理搞清楚了,讓我們回到一開始提到的問題,如何控制Toast的顯示時長?

  思路1:通過反射的方式調用TN類中的show和hide方法。

  代碼大概像這樣:

Object obj = message.obj;  
Method method =  obj.getClass().getDeclaredMethod("hide", null);  
method.invoke(obj, null); 

  但是很可惜,Method method =  obj.getClass().getDeclaredMethod("hide", null);  這種方法在4.0之上已經不適用了。

  思路2:不讓Toast進入系統隊列,我們自己維護一個隊列。

  這種方式其實仿照一下TN類中的實現,結合LinkedBlockingQueue和WindowManager就可以了。關於如何實現,后面有相應的源碼鏈接。

3、Toast在某些系統無法顯示問題

  此問題常見於小米系統。MIUI上可能是出於“綠化”的考慮,在維護Toast隊列的時候,Toast只能在自己進程運行在頂端的時候才能彈出來,否則就“invisible to user”。亂改系統行為,簡直喪心病狂有木有,最終苦的是廣大Android開發人員。不過有了上面的理論准備,要解決也是沒有問題的,參照思路2。

  對於這個問題,已經有人給出了源碼實現,請參考問題描述:解決小米MIUI系統上后台應用沒法彈Toast的問題Github源碼地址:https://github.com/zhitaocai/ToastCompat

  本來到這里就可以結束了,但筆者在實際開發中遭遇了一個小小的坑。

mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

  這個坑就是上面的mContext,它必須是ApplicationContext,不然在小米3或小米Note(Android 4.4.4)無法起作用!

  以上。

 

參考:

Android SDK - Toast

Toast相關源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM