日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

彻底理解Toast原理和解决小米MIUI系统上没法弹Toast的问题

發(fā)布時(shí)間:2023/12/13 综合教程 20 生活家
生活随笔 收集整理的這篇文章主要介紹了 彻底理解Toast原理和解决小米MIUI系统上没法弹Toast的问题 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、Toast的基本使用

  Toast在Android中屬于系統(tǒng)消息通知,用來提示用戶完成了什么操作、或者給用戶一個(gè)必要的提醒。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.

  它僅僅用作一個(gè)簡單的反饋機(jī)制。使用也比較簡單:

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

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

  一般情況下,我們傳入一個(gè)String就基本上滿足大多數(shù)的需求。但要想自定義一個(gè)View,然后通過Toast進(jìn)行顯示,也僅僅多了設(shè)置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>

  我們把這個(gè)文件命名為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();

  其實(shí)就是這么簡單。

2、Toast原理解剖

  但現(xiàn)實(shí)是,產(chǎn)品需求說你給我控制Toast顯示的時(shí)間。咋一看好像也不難嘛。

  不是有個(gè)setDuration方法么?當(dāng)你翻看源碼的時(shí)候,你會(huì)發(fā)現(xiàn)它的描述參數(shù)只有以下兩種:

LENGTH_SHORT
LENGTH_LONG

  這兩個(gè)常量對應(yīng)著2秒和3.5秒,你傳個(gè)其它數(shù)字進(jìn)入,效果并不是你所預(yù)料。其實(shí)這兩個(gè)常量僅僅是個(gè)flag,并不是我們想的多少秒。官方API文檔告訴我們:

This time could be user-definable.

  但,它又不提供一個(gè)公開的方法讓你設(shè)置。抓狂!先看一下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
    }
}

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

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

  看到Stub.asInterface,我們知道這是利用Binder進(jìn)行跨進(jìn)程調(diào)用了。而TN類就是遵循AIDL的實(shí)現(xiàn)。

private static class TN extends ITransientNotification.Stub

  TN類內(nèi)部使用Handler機(jī)制:post一個(gè)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()方法的實(shí)現(xiàn):

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方法實(shí)現(xiàn)Toast的顯示。其中trySendAccessibilityEvent()方法會(huì)把當(dāng)前的類名、應(yīng)用的包名通過AccessibilityManager來做進(jìn)一步的分發(fā),以供后續(xù)的處理。

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方法的最終實(shí)現(xiàn)在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

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

獲取當(dāng)前進(jìn)程的Id。
查看這個(gè)Toast是否在隊(duì)列中,有的話直接返回,并更新顯示時(shí)間。
如果是非系統(tǒng)的Toast(通過應(yīng)用包名進(jìn)行判斷),且Toast的總數(shù)大于等于50,不再把新的Toast放入隊(duì)列。
最后通過keepProcessAliveLocked(callingPid)方法來設(shè)置對應(yīng)的進(jìn)程為前臺(tái)進(jìn)程,保證不被銷毀。
如果index = 0,說明Toast就處于隊(duì)列的頭部,直接進(jìn)行顯示。
我們在NotificationManagerService類中確認(rèn)了前面提到的LENGTH_SHORT和LENGTH_LONG的顯示時(shí)長。

  關(guān)于上述的第四點(diǎn),我們通過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;

  所以一旦應(yīng)用被銷毀,它對應(yīng)的Toast也將不會(huì)再顯示:shows only on the owning user's window. 再來看這個(gè)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是一個(gè)ActivityManagerService實(shí)例,所以調(diào)用最終進(jìn)入到ActivityManagerService的setProcessForeground方法進(jìn)行再次處理。下面我用一張序列圖展示整個(gè)調(diào)用流程:

  其中第八步的scheduleTimeoutLocked()實(shí)質(zhì)上就是利用Handler延時(shí)發(fā)送一個(gè)Message,回調(diào)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的顯示和隱藏已經(jīng)分析完畢。原理搞清楚了,讓我們回到一開始提到的問題,如何控制Toast的顯示時(shí)長?

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

  代碼大概像這樣:

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

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

  思路2:不讓Toast進(jìn)入系統(tǒng)隊(duì)列,我們自己維護(hù)一個(gè)隊(duì)列。

  這種方式其實(shí)仿照一下TN類中的實(shí)現(xiàn),結(jié)合LinkedBlockingQueue和WindowManager就可以了。關(guān)于如何實(shí)現(xiàn),后面有相應(yīng)的源碼鏈接。

3、Toast在某些系統(tǒng)無法顯示問題

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

  對于這個(gè)問題,已經(jīng)有人給出了源碼實(shí)現(xiàn),請參考問題描述:解決小米MIUI系統(tǒng)上后臺(tái)應(yīng)用沒法彈Toast的問題,Github源碼地址:https://github.com/zhitaocai/ToastCompat

  本來到這里就可以結(jié)束了,但筆者在實(shí)際開發(fā)中遭遇了一個(gè)小小的坑。

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

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

  以上。

參考:

Android SDK - Toast

Toast相關(guān)源碼

總結(jié)

以上是生活随笔為你收集整理的彻底理解Toast原理和解决小米MIUI系统上没法弹Toast的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。