分析下Toast源码
我们常用Toast.makeText()方法创建Toast对象
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
//创建系统默认的Toast布局
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
//布局中的TextView
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
//view和duration赋值给Toast的全局变量
result.mNextView = v;
result.mDuration = duration;
return result;
}
//重载方法,可传字符串资源
public static Toast makeText(Context context, @StringRes int resId, @Duration int duration)
throws Resources.NotFoundException {
return makeText(context, context.getResources().getText(resId), duration);
}
Toast构造方法
final Context mContext;
final TN mTN;
int mDuration;
View mNextView;
public Toast(Context context) {
mContext = context;
mTN = new TN();
mTN.mY = context.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.toast_y_offset);
mTN.mGravity = context.getResources().getInteger(
com.android.internal.R.integer.config_toastDefaultGravity);
}
TN是Toast的静态内部类,继承自ITransientNotification.Stub用于IPC
private static class TN extends ITransientNotification.Stub{
}
通过makeText()方法创建Toast对象后调用show()方法显示
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
}
}
private static INotificationManager sService;
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
//AIDL 获取服务端代理对象
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
NotificationManagerService中INotificationManager.Stub.enqueueToast()
//callback即TN
@Override
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
...
synchronized (mToastQueue) {
int callingPid = Binder.getCallingPid();
long callingId = Binder.clearCallingIdentity();
try {
ToastRecord record;
int index;
if (!isSystemToast) {
index = indexOfToastPackageLocked(pkg);
} else {
index = indexOfToastLocked(pkg, callback);
}
if (index >= 0) {
record = mToastQueue.get(index);
record.update(duration);
try {
record.callback.hide();
} catch (RemoteException e) {
}
record.update(callback);
} else {
Binder token = new Binder();
mWindowManagerInternal.addWindowToken(token, TYPE_TOAST, DEFAULT_DISPLAY);
record = new ToastRecord(callingPid, pkg, callback, duration, token);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
}
keepProcessAliveIfNeededLocked(callingPid);
if (index == 0) {
//重点
showNextToastLocked();
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}
NotificationManagerService.ToastRecord TN的包装类
private static final class ToastRecord
{
//进程id
final int pid;
//包名
final String pkg;
//TN
ITransientNotification callback;
//显示时长
int duration;
//token
Binder token;
ToastRecord(int pid, String pkg, ITransientNotification callback, int duration,
Binder token) {
this.pid = pid;
this.pkg = pkg;
this.callback = callback;
this.duration = duration;
this.token = token;
}
void update(int duration) {
this.duration = duration;
}
void update(ITransientNotification callback) {
this.callback = callback;
}
void dump(PrintWriter pw, String prefix, DumpFilter filter) {
if (filter != null && !filter.matches(pkg)) return;
pw.println(prefix + this);
}
@Override
public final String toString()
{
return "ToastRecord{"
+ Integer.toHexString(System.identityHashCode(this))
+ " pkg=" + pkg
+ " callback=" + callback
+ " duration=" + duration;
}
}
NotificationManagerService.showNextToastLocked()
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
try {
//重点,最终还是调用TN.Show()
record.callback.show(record.token);
//显示duration时长后取消Toast
scheduleDurationReachedLocked(record);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to show notification " + record.callback
+ " in package " + record.pkg);
int index = mToastQueue.indexOf(record);
if (index >= 0) {
mToastQueue.remove(index);
}
keepProcessAliveIfNeededLocked(record.pid);
if (mToastQueue.size() > 0) {
record = mToastQueue.get(0);
} else {
record = null;
}
}
}
}
NotificationManagerService.scheduleDurationReachedLocked()
private void scheduleDurationReachedLocked(ToastRecord r)
{
mHandler.removeCallbacksAndMessages(r);
Message m = Message.obtain(mHandler, MESSAGE_DURATION_REACHED, r);
long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
mHandler.sendMessageDelayed(m, delay);
}
mHandler是WorkerHandler
WorkerHandler.handleMessage()
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_DURATION_REACHED:
handleDurationReached((ToastRecord)msg.obj);
break;
...
}
}
NotificationManagerService.handleDurationReached()
private void handleDurationReached(ToastRecord record)
{
if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}
NotificationManagerService.cancelToastLocked()
void cancelToastLocked(int index) {
ToastRecord record = mToastQueue.get(index);
try {
//最终调用TN.hide()
record.callback.hide();
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to hide notification " + record.callback
+ " in package " + record.pkg);
}
...
}
Toast.show()方法通过binder机制获取NMS代理对象,然后调用服务端enqueueToast()方法将Toast内部类TN做为回调对象传入。NMS经过一系列调用最终回调到TN.show()方法显示Toast,并在显示Duration时长后回调TN.hide()方法取消Toast。
接下来看TN.show()
final Handler mHandler = new Handler();
public void show() {
mHandler.post(mShow);
}
public void hide() {
mHandler.post(mHide);
}
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
mNextView = null;
}
};
TN.handleShow() 这里只贴重点
public void handleShow() {
if (mView != mNextView) {
// remove the old view if necessary
handleHide();
mView = mNextView;
mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
mWM.addView(mView, mParams);
}
}
通过WindowManager.addView()来显示View。流程前面有讲Android Activity、Window、View
TN.handleHide()
public void handleHide() {
if (mView != null) {
if (mView.getParent() != null) {
mWM.removeView(mView);
}
mView = null;
}
}
通过WindowManager.removeView()取消显示。流程前面有讲Dialog 源码分析
自定义Toast
Toast toast = new Toast(context);
View view = LayoutInflater.from(context).inflate(R.layout.toast, null);
TextView tvContent = (TextView) view.findViewById(R.id.tvContentToast);
tvContent.setText(msg);
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
网友评论