android framework/base 看源码实战:控制Toast显示时长(提供在线看源码地址)
来源:互联网 发布:酷狗音乐软件版本 编辑:程序博客网 时间:2024/05/03 10:56
来源/转自:http://www.2cto.com/kf/201410/347560.html
资源提供:
没下载的在线看源码(包括framwork/base):https://gitorious.org/0xdroid/frameworks_base/source/9c3abacea52f4e03f1de745126a5dd28d269894f:
前言
对于Toast不甚了解,可以参考我的上一篇博客《Android:谈一谈安卓应用中的Toast情节》,里面有关于Toast基础比较详细的介绍。
如果你想要看的是最原汁原味的Toast攻略,请谷歌。
一起分析一下Toast的源码设计吧
如果你想要看的是最原汁原味的Toast攻略,请谷歌。
一起分析一下Toast的源码设计吧
Toast的源代码世界
点进了这个代码文件,发现了这么一个函数public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
瞄了几眼代码,发现Toast显示的布局文件是transient_notification.xml!怀揣这洋洋得意的心思,在源代码中开始搜索transient_notification.xml,一顿卡死,终于在快放弃的时候给出了结果。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="?android:attr/toastFrameBackground">
<TextView
android:id="@android:id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textAppearance="@style/TextAppearance.Toast"
android:textColor="@color/bright_foreground_dark"
android:shadowColor="#BB000000"
android:shadowRadius="2.75"
/>
</LinearLayout>
接下来看什么呢,肯定是show()方法了。public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getPackageName();
TN tn = mTN;
tn.mNextView = mNextView;
try {
service.enqueueToast(pkg, tn, mDuration);
} catch (RemoteException e) {
// Empty
}
}
这里好像是要先获取一个服务:INotificationManager,
然后调用service.enqueueToast(pkg, tn, mDuration)好像是将Toast放到一个队列里面显示吧;
这个TN是个啥子玩意呢?代码搜索(ctrl + f,输入TN):
然后调用service.enqueueToast(pkg, tn, mDuration)好像是将Toast放到一个队列里面显示吧;
这个TN是个啥子玩意呢?代码搜索(ctrl + f,输入TN):
复制代码
private static class TN extends ITransientNotification.Stub {
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;
}
};
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
final Handler mHandler = new Handler();
int mGravity;
int mX, mY;
float mHorizontalMargin;
float mVerticalMargin;
View mView;
View mNextView;
WindowManager mWM;
TN() {
// XXX This should be changed to use a Dialog, with a Theme.Toast
// defined that sets up the layout params appropriately.
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
}
/**
* schedule handleShow into the right thread
*/
@Override
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
/**
* schedule handleHide into the right thread
*/
@Override
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
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();
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;
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();
}
}
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);
}
public void handleHide() {
if (localLOGV) Log.v(TAG, "HANDLE HIDE: " + this + " mView=" + mView);
if (mView != null) {
// note: checking parent() just to make sure the view has
// been added... i have seen cases where we get here when
// the view isn't yet added, so let's try not to crash.
if (mView.getParent() != null) {
if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
mView = null;
}
}
}
这个TN继承了ITransientNotification.Stub,
在源代码中找了一下:ITransientNotification
发现ITransientNotification.aidl
打开ITransientNotification瞄一瞄,发现了show()和hide()这两个方法。
在源代码中找了一下:ITransientNotification
发现ITransientNotification.aidl
打开ITransientNotification瞄一瞄,发现了show()和hide()这两个方法。
package android.app;
/** @hide */
oneway interface ITransientNotification {
void show();
void hide();
}
回去TN看看他的实现了
复制代码
@Override
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
@Override
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
原来是使用handler机制,分别post一个nShow和一个mHide
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
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();
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;
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();
}
}
原来是Toast的视图是通过WindowManager的addView来加载的
将目光定位在TN()这个构造方法上
TN() {
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
}
这就是设置Toast中的View的各种位置参数params。
其实Toast的原理是这样的:
先通过makeText()实例化出一个Toast,然后调用toast.Show()方法,
这时并不会马上显示Toast,而是会实例化一个TN变量,然后通过service.enqueueToast()将其加到服务队列里面去等待显示。
在TN中进行调控Toast的显示格式以及里面的hide()、show()方法来控制Toast的出现以及消失,强调一下的是这个队列是系统维护的,我们并不能干涉。
先通过makeText()实例化出一个Toast,然后调用toast.Show()方法,
这时并不会马上显示Toast,而是会实例化一个TN变量,然后通过service.enqueueToast()将其加到服务队列里面去等待显示。
在TN中进行调控Toast的显示格式以及里面的hide()、show()方法来控制Toast的出现以及消失,强调一下的是这个队列是系统维护的,我们并不能干涉。
自由控制Toast的显示时间
需求: 给应用设置一个较长时间的Toast。
但是不管怎么设置,Toast只能有显示2s和3.5s这两个情况
但是不管怎么设置,Toast只能有显示2s和3.5s这两个情况
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);
}
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
我们看到这里是使用了handler中的延迟发信息来显示toast的,这里我们也看到了,延迟时间是duration,但是只有两个值:2s和3.5s这两个值,
Toast的显示是首先借助TN类,所有的显示逻辑在这个类中的show方法中,然后再实例一个TN类变量,将传递到一个队列中进行显示,所以我们要向解决这个显示的时间问题,那就从入队列这部给截断,说白了就两点:
1、不让Toast进入队列
2、调用TN类中的hide和show的方法自己控制Toast
但是第一点好实现,第二点让人抓狂了,因为我们看到TN这个类是私有的,所以我们也不能实例化他的对象,但是toast类中有一个实例化对象:tn
final TN mTN;
包访问权限,得借助无比强大的反射技术,我们只需要反射出这个变量,然后强暴她一次即可,
得到这个变量我们可以得到这个TN类对象了,然后再使用反射获取他的show和hide方法即可,代码如下:
得到这个变量我们可以得到这个TN类对象了,然后再使用反射获取他的show和hide方法即可,代码如下:
方法一:
public class ToastReflect {
private Toast mToast;
private Field field;
private Object obj;
private Method showMethod, hideMethod;
private double time;
private ToastReflect(Context context, String text, double time){
this.time = time;
mToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
reflectionTN();
}
private void reflectionTN() {
try{
field = mToast.getClass().getDeclaredField("mTN");
field.setAccessible(true);
obj = field.get(mToast);
showMethod = obj.getClass().getDeclaredMethod("show", null);
hideMethod = obj.getClass().getDeclaredMethod("hide", null);
}catch(Exception e){
e.printStackTrace();
}
}
public static ToastReflect makeText(Context context, String text, double time){
ToastReflect toastReflect = new ToastReflect(context, text, time);
return toastReflect;
}
private void showToast(){
try{
showMethod.invoke(obj, null);
}catch(Exception e){
e.printStackTrace();
}
}
private void hideToast(){
try{
hideMethod.invoke(obj, null);
}catch(Exception e){
e.printStackTrace();
}
}
public void show(){
showToast();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
hideToast();
}
}, (long)(time * 1000));
}
}
ps:利用反射来控制Toast的显示时间在高版本会有bug,Android 2.2实测实可以用的,Android 4.0则无法使用。具体原因大牛还在分析。。。。。。
方法二:
但是作为一个通用性软件,对于任何版本都需要支持,所以还是只能采取其他办法,发现了一个比较傻瓜的实现。
就是可以利用handler.post结合timer来实现效果,兼容性较好。。利用定时重复show一个Toast就能达到根据特定时间来显示的功能。
public class ToastSimple {
private double time;
private static Handler handler;
private Timer showTimer;
private Timer cancelTimer;
private Toast toast;
private ToastSimple(){
showTimer = new Timer();
cancelTimer = new Timer();
}
public void setTime(double time) {
this.time = time;
}
public void setToast(Toast toast){
this.toast = toast;
}
public static ToastSimple makeText(Context context, String text, double time){
ToastSimple toast1= new ToastSimple();
toast1.setTime(time);
toast1.setToast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
handler = new Handler(context.getMainLooper());
return toast1;
}
public void show(){
toast.show();
if(time > 2){
showTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new ShowRunnable());
}
}, 0, 1900);
}
cancelTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new CancelRunnable());
}
}, (long)(time * 1000));
}
private class CancelRunnable implements Runnable{
@Override
public void run() {
showTimer.cancel();
toast.cancel();
}
}
private class ShowRunnable implements Runnable{
@Override
public void run() {
toast.show();
}
}
}
方法三:
因为Toast是基于windowManager来显示的,所以完全可以自己写一个自定义的Toast,代码如下
package com.net168.toast;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
public class ToastCustom {
private WindowManager wdm;
private double time;
private View mView;
private WindowManager.LayoutParams params;
private Timer timer;
private ToastCustom(Context context, String text, double time){
wdm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
timer = new Timer();
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
mView = toast.getView();
params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = toast.getView().getAnimation().INFINITE;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
params.y = -30;
this.time = time;
}
public static ToastCustom makeText(Context context, String text, double time){
ToastCustom toastCustom = new ToastCustom(context, text, time);
return toastCustom;
}
public void show(){
wdm.addView(mView, params);
timer.schedule(new TimerTask() {
@Override
public void run() {
wdm.removeView(mView);
}
}, (long)(time * 1000));
}
public void cancel(){
wdm.removeView(mView);
timer.cancel();
}
}
PS:上面自定义Toast代码只实现了基本功能,其余功能由于时间关系没有全部实现。
测试代码如下:
public class MainActivity extends ActionBarActivity implements View.OnClickListener{
private EditText edt_duration;
private Button btn_toast_simple;
private Button btn_toast_reflect;
private Button btn_toast_custom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_duration = (EditText) findViewById(R.id.edt_duration);
btn_toast_simple = (Button) findViewById(R.id.btn_toast_simple);
btn_toast_reflect = (Button) findViewById(R.id.btn_toast_reflect);
btn_toast_custom = (Button) findViewById(R.id.btn_toast_custom);
btn_toast_simple.setOnClickListener(this);
btn_toast_reflect.setOnClickListener(this);
btn_toast_custom.setOnClickListener(this);
}
@Override
public void onClick(View v) {
double time = Double.parseDouble((edt_duration.getText().toString()));
switch (v.getId()){
case R.id.btn_toast_simple:
ToastSimple.makeText(MainActivity.this, "简单Toast,执行时间为:" + time, time).show();
break;
case R.id.btn_toast_reflect:
ToastReflect.makeText(MainActivity.this, "反射Toast,执行时间为" + time, time).show();
break;
case R.id.btn_toast_custom:
ToastCustom.makeText(MainActivity.this, "反射Toast,执行时间为" + time, time).show();
break;
}
}
}
0 0
- android framework/base 看源码实战:控制Toast显示时长(提供在线看源码地址)
- 在线看Android源码
- Android:剖析源码,随心所欲控制Toast显示
- Android:剖析源码,随心所欲控制Toast显示
- Android 各个版本源码在线看
- 安卓在线看源码
- android在线源码地址
- 一个在线看android系统各个版本源码的链接
- Toast源码分析 控制显示时间
- Android下查询系统源码看短信的显示
- Android下查询系统源码看短信的显示
- android:源码在线查看地址
- android源码在线阅读地址
- Android 源码在线查看地址
- 看 android omx 源码有感
- Android 看IntentService源码延伸
- Android FragmentTabHost看源码延伸
- 看android源码的方式
- ubuntu dns,gateway
- Python标准库:内置函数list([iterable])
- C/C++语言中内容完全相同的多个函数,使用宏函数的写法
- C++ 新旧代码的兼容
- jQuery Mobile基础知识学习
- android framework/base 看源码实战:控制Toast显示时长(提供在线看源码地址)
- [2]vs2010配备boost编程环境
- ogg_单项同步_dml
- Android Studio环境搭建(随手记下备忘)
- oracle定时器job(定时存储过程)
- HDU-2539-点球大战
- ogg_单项同步_ddl
- 两个线程同时调用同一个处理函数的互斥问题
- ogg_rman 初始化