Android桌面悬浮窗效果实现,仿360手机卫士悬浮窗效果
出处:http://blog.csdn.net/guolin_blog/article/details/8689140
大家好,今天给大家带来一个仿360手机卫士悬浮窗效果的教程,在开始之前请允许我说几句不相干的废话。
不知不觉我发现自己接触Android已有近三个年头了,期间各种的成长少不了各位高手的帮助,总是有很多高手喜欢把自己的经验写在网上,供大家来学习,我也是从中受惠了很多,在此我深表感谢。可是我发现我却从来没有将自己平时的一些心得拿出来与大家分享,共同学习,太没有奉献精神了。于是我痛定思痛,决定从今天开始写博客,希望可以指点在我后面的开发者,更快地进入Android开发者的行列当中。
好了,废话就说这么多,下面开始进入今天的主题吧。
360手机卫士我相信大家都知道,好多人手机上都会装这一款软件,那么我们对它的一个桌面悬浮窗效果想必都不会陌生。请看下图:
首先是一个小的悬浮窗显示的是当前使用了百分之多少的内存,点击一下小悬浮窗,就会弹出一个大的悬浮窗,可以一键加速。好,我们现在就来模拟实现一下类似的效果。
先谈一下基本的实现原理,这种桌面悬浮窗的效果很类似与Widget,但是它比Widget要灵活的多。主要是通过WindowManager这个类来实现的,调用这个类的addView方法用于添加一个悬浮窗,updateViewLayout方法用于更新悬浮窗的参数,removeView用于移除悬浮窗。其中悬浮窗的参数有必要详细说明一下。
WindowManager.LayoutParams这个类用于提供悬浮窗所需的参数,其中有几个经常会用到的变量:
type值用于确定悬浮窗的类型,一般设为2002,表示在所有应用程序之上,但在状态栏之下。
flags值用于确定悬浮窗的行为,比如说不可聚焦,非模态对话框等等,属性非常多,大家可以查看文档。
gravity值用于确定悬浮窗的对齐方式,一般设为左上角对齐,这样当拖动悬浮窗的时候方便计算坐标。
x值用于确定悬浮窗的位置,如果要横向移动悬浮窗,就需要改变这个值。
y值用于确定悬浮窗的位置,如果要纵向移动悬浮窗,就需要改变这个值。
width值用于指定悬浮窗的宽度。
height值用于指定悬浮窗的高度。
创建悬浮窗这种窗体需要向用户申请权限才可以的,因此还需要在AndroidManifest.xml中加入<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
原理介绍完了,下面我们开始用代码实现。首先在Eclipse中新建一个Android项目,项目名就叫做360FloatWindowDemo。然后写一下布局文件,布局文件非常简单,只有一个按钮,打开或新建activity_main.xml,加入如下代码:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- tools:context=".MainActivity" >
- <Button
- android:id="@+id/start_float_window"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Start Float Window" >
- </Button>
- </RelativeLayout>
然后再新建一个名为float_window_small.xml的布局文件,用于做为小悬浮窗的布局,在其中加入如下代码:
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/small_window_layout"
- android:layout_width="60dip"
- android:layout_height="25dip"
- android:background="@drawable/bg_small"
- >
- <TextView
- android:id="@+id/percent"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center"
- android:textColor="#ffffff"
- />
- </LinearLayout>
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/big_window_layout"
- android:layout_width="200dip"
- android:layout_height="100dip"
- android:background="@drawable/bg_big"
- android:orientation="vertical"
- >
- <Button
- android:id="@+id/close"
- android:layout_width="100dip"
- android:layout_height="40dip"
- android:layout_gravity="center_horizontal"
- android:layout_marginTop="12dip"
- android:text="关闭悬浮窗"
- />
- <Button
- android:id="@+id/back"
- android:layout_width="100dip"
- android:layout_height="40dip"
- android:layout_gravity="center_horizontal"
- android:text="返回"
- />
- </LinearLayout>
然后打开或创建MainActivity,这是项目的主界面,在里面加入如下代码:
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button startFloatWindow = (Button) findViewById(R.id.start_float_window);
- startFloatWindow.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- Intent intent = new Intent(MainActivity.this, FloatWindowService.class);
- startService(intent);
- finish();
- }
- });
- }
- }
- public class FloatWindowService extends Service {
- /**
- * 用于在线程中创建或移除悬浮窗。
- */
- private Handler handler = new Handler();
- /**
- * 定时器,定时进行检测当前应该创建还是移除悬浮窗。
- */
- private Timer timer;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // 开启定时器,每隔0.5秒刷新一次
- if (timer == null) {
- timer = new Timer();
- timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);
- }
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- // Service被终止的同时也停止定时器继续运行
- timer.cancel();
- timer = null;
- }
- class RefreshTask extends TimerTask {
- @Override
- public void run() {
- // 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。
- if (isHome() && !MyWindowManager.isWindowShowing()) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- MyWindowManager.createSmallWindow(getApplicationContext());
- }
- });
- }
- // 当前界面不是桌面,且有悬浮窗显示,则移除悬浮窗。
- else if (!isHome() && MyWindowManager.isWindowShowing()) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- MyWindowManager.removeSmallWindow(getApplicationContext());
- MyWindowManager.removeBigWindow(getApplicationContext());
- }
- });
- }
- // 当前界面是桌面,且有悬浮窗显示,则更新内存数据。
- else if (isHome() && MyWindowManager.isWindowShowing()) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- MyWindowManager.updateUsedPercent(getApplicationContext());
- }
- });
- }
- }
- }
- /**
- * 判断当前界面是否是桌面
- */
- private boolean isHome() {
- ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
- return getHomes().contains(rti.get(0).topActivity.getPackageName());
- }
- /**
- * 获得属于桌面的应用的应用包名称
- *
- * @return 返回包含所有包名的字符串列表
- */
- private List<String> getHomes() {
- List<String> names = new ArrayList<String>();
- PackageManager packageManager = this.getPackageManager();
- Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.addCategory(Intent.CATEGORY_HOME);
- List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
- PackageManager.MATCH_DEFAULT_ONLY);
- for (ResolveInfo ri : resolveInfo) {
- names.add(ri.activityInfo.packageName);
- }
- return names;
- }
- }
从上面的代码我们也可以看出,创建和移除悬浮窗,以及更新悬浮窗内的数据,都是由MyWindowManager这个类来管理的,比起直接把这些代码写在Activity或Service当中,使用一个专门的工具类来管理要好的多。不过要想创建悬浮窗,还是先要把悬浮窗的View写出来。
新建一个名叫FloatWindowSmallView的类,继承自LinearLayout。新建一个名叫FloatWindowBigView的类,也继承自LinearLayout。
在FloatWindowSmallView中加入如下代码:
- public class FloatWindowSmallView extends LinearLayout {
- /**
- * 记录小悬浮窗的宽度
- */
- public static int viewWidth;
- /**
- * 记录小悬浮窗的高度
- */
- public static int viewHeight;
- /**
- * 记录系统状态栏的高度
- */
- private static int statusBarHeight;
- /**
- * 用于更新小悬浮窗的位置
- */
- private WindowManager windowManager;
- /**
- * 小悬浮窗的参数
- */
- private WindowManager.LayoutParams mParams;
- /**
- * 记录当前手指位置在屏幕上的横坐标值
- */
- private float xInScreen;
- /**
- * 记录当前手指位置在屏幕上的纵坐标值
- */
- private float yInScreen;
- /**
- * 记录手指按下时在屏幕上的横坐标的值
- */
- private float xDownInScreen;
- /**
- * 记录手指按下时在屏幕上的纵坐标的值
- */
- private float yDownInScreen;
- /**
- * 记录手指按下时在小悬浮窗的View上的横坐标的值
- */
- private float xInView;
- /**
- * 记录手指按下时在小悬浮窗的View上的纵坐标的值
- */
- private float yInView;
- public FloatWindowSmallView(Context context) {
- super(context);
- windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
- View view = findViewById(R.id.small_window_layout);
- viewWidth = view.getLayoutParams().width;
- viewHeight = view.getLayoutParams().height;
- TextView percentView = (TextView) findViewById(R.id.percent);
- percentView.setText(MyWindowManager.getUsedPercentValue(context));
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
- xInView = event.getX();
- yInView = event.getY();
- xDownInScreen = event.getRawX();
- yDownInScreen = event.getRawY() - getStatusBarHeight();
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- break;
- case MotionEvent.ACTION_MOVE:
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- // 手指移动的时候更新小悬浮窗的位置
- updateViewPosition();
- break;
- case MotionEvent.ACTION_UP:
- // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
- if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
- openBigWindow();
- }
- break;
- default:
- break;
- }
- return true;
- }
- /**
- * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
- *
- * @param params
- * 小悬浮窗的参数
- */
- public void setParams(WindowManager.LayoutParams params) {
- mParams = params;
- }
- /**
- * 更新小悬浮窗在屏幕中的位置。
- */
- private void updateViewPosition() {
- mParams.x = (int) (xInScreen - xInView);
- mParams.y = (int) (yInScreen - yInView);
- windowManager.updateViewLayout(this, mParams);
- }
- /**
- * 打开大悬浮窗,同时关闭小悬浮窗。
- */
- private void openBigWindow() {
- MyWindowManager.createBigWindow(getContext());
- MyWindowManager.removeSmallWindow(getContext());
- }
- /**
- * 用于获取状态栏的高度。
- *
- * @return 返回状态栏高度的像素值。
- */
- private int getStatusBarHeight() {
- if (statusBarHeight == 0) {
- try {
- Class<?> c = Class.forName("com.android.internal.R$dimen");
- Object o = c.newInstance();
- Field field = c.getField("status_bar_height");
- int x = (Integer) field.get(o);
- statusBarHeight = getResources().getDimensionPixelSize(x);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return statusBarHeight;
- }
在FloatWindowBigView中加入如下代码:
- public class FloatWindowBigView extends LinearLayout {
- /**
- * 记录大悬浮窗的宽度
- */
- public static int viewWidth;
- /**
- * 记录大悬浮窗的高度
- */
- public static int viewHeight;
- public FloatWindowBigView(final Context context) {
- super(context);
- LayoutInflater.from(context).inflate(R.layout.float_window_big, this);
- View view = findViewById(R.id.big_window_layout);
- viewWidth = view.getLayoutParams().width;
- viewHeight = view.getLayoutParams().height;
- Button close = (Button) findViewById(R.id.close);
- Button back = (Button) findViewById(R.id.back);
- close.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // 点击关闭悬浮窗的时候,移除所有悬浮窗,并停止Service
- MyWindowManager.removeBigWindow(context);
- MyWindowManager.removeSmallWindow(context);
- Intent intent = new Intent(getContext(), FloatWindowService.class);
- context.stopService(intent);
- }
- });
- back.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // 点击返回的时候,移除大悬浮窗,创建小悬浮窗
- MyWindowManager.removeBigWindow(context);
- MyWindowManager.createSmallWindow(context);
- }
- });
- }
- }
现在两个悬浮窗的View都已经写好了,我们来创建MyWindowManager,代码如下:
- public class MyWindowManager {
- /**
- * 小悬浮窗View的实例
- */
- private static FloatWindowSmallView smallWindow;
- /**
- * 大悬浮窗View的实例
- */
- private static FloatWindowBigView bigWindow;
- /**
- * 小悬浮窗View的参数
- */
- private static LayoutParams smallWindowParams;
- /**
- * 大悬浮窗View的参数
- */
- private static LayoutParams bigWindowParams;
- /**
- * 用于控制在屏幕上添加或移除悬浮窗
- */
- private static WindowManager mWindowManager;
- /**
- * 用于获取手机可用内存
- */
- private static ActivityManager mActivityManager;
- /**
- * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
- *
- * @param context
- * 必须为应用程序的Context.
- */
- public static void createSmallWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (smallWindow == null) {
- smallWindow = new FloatWindowSmallView(context);
- if (smallWindowParams == null) {
- smallWindowParams = new LayoutParams();
- smallWindowParams.type = LayoutParams.TYPE_PHONE;
- smallWindowParams.format = PixelFormat.RGBA_8888;
- smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
- | LayoutParams.FLAG_NOT_FOCUSABLE;
- smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- smallWindowParams.width = FloatWindowSmallView.viewWidth;
- smallWindowParams.height = FloatWindowSmallView.viewHeight;
- smallWindowParams.x = screenWidth;
- smallWindowParams.y = screenHeight / 2;
- }
- smallWindow.setParams(smallWindowParams);
- windowManager.addView(smallWindow, smallWindowParams);
- }
- }
- /**
- * 将小悬浮窗从屏幕上移除。
- *
- * @param context
- * 必须为应用程序的Context.
- */
- public static void removeSmallWindow(Context context) {
- if (smallWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(smallWindow);
- smallWindow = null;
- }
- }
- /**
- * 创建一个大悬浮窗。位置为屏幕正中间。
- *
- * @param context
- * 必须为应用程序的Context.
- */
- public static void createBigWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (bigWindow == null) {
- bigWindow = new FloatWindowBigView(context);
- if (bigWindowParams == null) {
- bigWindowParams = new LayoutParams();
- bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2;
- bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2;
- bigWindowParams.type = LayoutParams.TYPE_PHONE;
- bigWindowParams.format = PixelFormat.RGBA_8888;
- bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- bigWindowParams.width = FloatWindowBigView.viewWidth;
- bigWindowParams.height = FloatWindowBigView.viewHeight;
- }
- windowManager.addView(bigWindow, bigWindowParams);
- }
- }
- /**
- * 将大悬浮窗从屏幕上移除。
- *
- * @param context
- * 必须为应用程序的Context.
- */
- public static void removeBigWindow(Context context) {
- if (bigWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(bigWindow);
- bigWindow = null;
- }
- }
- /**
- * 更新小悬浮窗的TextView上的数据,显示内存使用的百分比。
- *
- * @param context
- * 可传入应用程序上下文。
- */
- public static void updateUsedPercent(Context context) {
- if (smallWindow != null) {
- TextView percentView = (TextView) smallWindow.findViewById(R.id.percent);
- percentView.setText(getUsedPercentValue(context));
- }
- }
- /**
- * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
- *
- * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
- */
- public static boolean isWindowShowing() {
- return smallWindow != null || bigWindow != null;
- }
- /**
- * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
- *
- * @param context
- * 必须为应用程序的Context.
- * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
- */
- private static WindowManager getWindowManager(Context context) {
- if (mWindowManager == null) {
- mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- }
- return mWindowManager;
- }
- /**
- * 如果ActivityManager还未创建,则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return ActivityManager的实例,用于获取手机可用内存。
- */
- private static ActivityManager getActivityManager(Context context) {
- if (mActivityManager == null) {
- mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- }
- return mActivityManager;
- }
- /**
- * 计算已使用内存的百分比,并返回。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 已使用内存的百分比,以字符串形式返回。
- */
- public static String getUsedPercentValue(Context context) {
- String dir = "/proc/meminfo";
- try {
- FileReader fr = new FileReader(dir);
- BufferedReader br = new BufferedReader(fr, 2048);
- String memoryLine = br.readLine();
- String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
- br.close();
- long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
- long availableSize = getAvailableMemory(context) / 1024;
- int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
- return percent + "%";
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "悬浮窗";
- }
- /**
- * 获取当前可用内存,返回数据以字节为单位。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 当前可用内存。
- */
- private static long getAvailableMemory(Context context) {
- ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
- getActivityManager(context).getMemoryInfo(mi);
- return mi.availMem;
- }
- }
到这里基本所有的代码都已经写完了,然后我们来看一下AndroidManifest.xml文件吧,里面代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.demo.floatwindowdemo"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="8" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.demo.floatwindowdemo.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name=".FloatWindowService"></service>
- </application>
- </manifest>
好了,现在让我们运行一下项目吧,效果如下图,主界面只有一个简单的按钮,点击按钮后,Activity被关闭,小悬浮窗显示在桌面上。其中显示着当前内存使用的百分比。
小悬浮窗是可以自由拖动的,如果打开了其它的应用程序,小悬浮窗会自动隐藏,回到桌面后小悬浮窗又会显示出来。
如果点击了小悬浮窗会弹出大悬浮窗来,这里我们大悬浮窗做的比较简单,就只有两个按钮。大悬浮窗展示的时候手机的所有其它程序是不可点的,因为焦点都在悬浮窗上了。点击返回按钮会重新展示小悬浮窗,点击关闭悬浮窗按钮,Service也会一起停掉。
360手机卫士的一键加速功能我们就不做了,就像独孤九剑一样,重要的是剑意而不是剑招,我相信大家学会了创建悬浮窗的基本原理后可以做出比360更有创意的东西。
如果大家还有什么疑问,请在下面留言。
对桌面悬浮窗感兴趣的朋友可以继续阅读 Android桌面悬浮窗进阶,QQ手机管家小火箭效果实现 。
补充:
出处:http://blog.csdn.net/guolin_blog/article/details/16919859
今天是2013年的最后一天了,这里首先提前祝大家新年快乐!同时,本篇文章也是我今年的最后一篇文章了,因此我想要让它尽量有点特殊性,比起平时的文章要多一些特色。记得在今年年初的时候,我写的第一篇文章是模仿360手机卫士的桌面悬浮窗效果,那么为了能够首尾呼应,今年的最后一篇文章就同样还是来实现桌面悬浮窗的效果吧,当然效果将会更加高级。
相信用过QQ手机管家的朋友们都会知道它有一个小火箭加速的功能,将小火箭拖动到火箭发射台上发射就会出现一个火箭升空的动画,那么今天我们就来模仿着实现一下这个效果吧。
这次我们将代码的重点放在火箭升空的效果上,因此简单起见,就直接在模仿360手机卫士悬浮窗的那份代码的基础上继续开发了,如果你还没有看过那篇文章的话,建议先去阅读 Android桌面悬浮窗效果实现,仿360手机卫士悬浮窗效果 。
比起普通的桌面悬浮窗,现在我们需要在拖动悬浮窗的时候将悬浮窗变成一个小火箭,并且在屏幕的底部添加一个火箭发射台。那么我们就从火箭发射台开始编写吧,首先创建launcher.xml作为火箭发射台的布局文件,如下所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- >
- <ImageView
- android:id="@+id/launcher_img"
- android:layout_width="200dp"
- android:layout_height="88dp"
- android:src="@drawable/launcher_bg_hold"
- />
- </LinearLayout>
接下来创建RocketLauncher类,作为火箭发射台的View,代码如下所示:
- public class RocketLauncher extends LinearLayout {
- /**
- * 记录火箭发射台的宽度
- */
- public static int width;
- /**
- * 记录火箭发射台的高度
- */
- public static int height;
- /**
- * 火箭发射台的背景图片
- */
- private ImageView launcherImg;
- public RocketLauncher(Context context) {
- super(context);
- LayoutInflater.from(context).inflate(R.layout.launcher, this);
- launcherImg = (ImageView) findViewById(R.id.launcher_img);
- width = launcherImg.getLayoutParams().width;
- height = launcherImg.getLayoutParams().height;
- }
- /**
- * 更新火箭发射台的显示状态。如果小火箭被拖到火箭发射台上,就显示发射。
- */
- public void updateLauncherStatus(boolean isReadyToLaunch) {
- if (isReadyToLaunch) {
- launcherImg.setImageResource(R.drawable.launcher_bg_fire);
- } else {
- launcherImg.setImageResource(R.drawable.launcher_bg_hold);
- }
- }
- }
新增的文件只有这两个,剩下的就是要修改之前的代码了。首先修改MyWindowManager中的代码,如下所示:
- public class MyWindowManager {
- /**
- * 小悬浮窗View的实例
- */
- private static FloatWindowSmallView smallWindow;
- /**
- * 大悬浮窗View的实例
- */
- private static FloatWindowBigView bigWindow;
- /**
- * 火箭发射台的实例
- */
- private static RocketLauncher rocketLauncher;
- /**
- * 小悬浮窗View的参数
- */
- private static LayoutParams smallWindowParams;
- /**
- * 大悬浮窗View的参数
- */
- private static LayoutParams bigWindowParams;
- /**
- * 火箭发射台的参数
- */
- private static LayoutParams launcherParams;
- /**
- * 用于控制在屏幕上添加或移除悬浮窗
- */
- private static WindowManager mWindowManager;
- /**
- * 用于获取手机可用内存
- */
- private static ActivityManager mActivityManager;
- /**
- * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
- */
- public static void createSmallWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (smallWindow == null) {
- smallWindow = new FloatWindowSmallView(context);
- if (smallWindowParams == null) {
- smallWindowParams = new LayoutParams();
- smallWindowParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
- smallWindowParams.format = PixelFormat.RGBA_8888;
- smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
- | LayoutParams.FLAG_NOT_FOCUSABLE;
- smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- smallWindowParams.width = FloatWindowSmallView.windowViewWidth;
- smallWindowParams.height = FloatWindowSmallView.windowViewHeight;
- smallWindowParams.x = screenWidth;
- smallWindowParams.y = screenHeight / 2;
- }
- smallWindow.setParams(smallWindowParams);
- windowManager.addView(smallWindow, smallWindowParams);
- }
- }
- /**
- * 将小悬浮窗从屏幕上移除。
- */
- public static void removeSmallWindow(Context context) {
- if (smallWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(smallWindow);
- smallWindow = null;
- }
- }
- /**
- * 创建一个大悬浮窗。位置为屏幕正中间。
- */
- public static void createBigWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (bigWindow == null) {
- bigWindow = new FloatWindowBigView(context);
- if (bigWindowParams == null) {
- bigWindowParams = new LayoutParams();
- bigWindowParams.x = screenWidth / 2
- - FloatWindowBigView.viewWidth / 2;
- bigWindowParams.y = screenHeight / 2
- - FloatWindowBigView.viewHeight / 2;
- bigWindowParams.type = LayoutParams.TYPE_PHONE;
- bigWindowParams.format = PixelFormat.RGBA_8888;
- bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- bigWindowParams.width = FloatWindowBigView.viewWidth;
- bigWindowParams.height = FloatWindowBigView.viewHeight;
- }
- windowManager.addView(bigWindow, bigWindowParams);
- }
- }
- /**
- * 将大悬浮窗从屏幕上移除。
- */
- public static void removeBigWindow(Context context) {
- if (bigWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(bigWindow);
- bigWindow = null;
- }
- }
- /**
- * 创建一个火箭发射台,位置为屏幕底部。
- */
- public static void createLauncher(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (rocketLauncher == null) {
- rocketLauncher = new RocketLauncher(context);
- if (launcherParams == null) {
- launcherParams = new LayoutParams();
- launcherParams.x = screenWidth / 2 - RocketLauncher.width / 2;
- launcherParams.y = screenHeight - RocketLauncher.height;
- launcherParams.type = LayoutParams.TYPE_PHONE;
- launcherParams.format = PixelFormat.RGBA_8888;
- launcherParams.gravity = Gravity.LEFT | Gravity.TOP;
- launcherParams.width = RocketLauncher.width;
- launcherParams.height = RocketLauncher.height;
- }
- windowManager.addView(rocketLauncher, launcherParams);
- }
- }
- /**
- * 将火箭发射台从屏幕上移除。
- */
- public static void removeLauncher(Context context) {
- if (rocketLauncher != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(rocketLauncher);
- rocketLauncher = null;
- }
- }
- /**
- * 更新火箭发射台的显示状态。
- */
- public static void updateLauncher() {
- if (rocketLauncher != null) {
- rocketLauncher.updateLauncherStatus(isReadyToLaunch());
- }
- }
- /**
- * 更新小悬浮窗的TextView上的数据,显示内存使用的百分比。
- *
- * @param context
- * 可传入应用程序上下文。
- */
- public static void updateUsedPercent(Context context) {
- if (smallWindow != null) {
- TextView percentView = (TextView) smallWindow
- .findViewById(R.id.percent);
- percentView.setText(getUsedPercentValue(context));
- }
- }
- /**
- * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
- *
- * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
- */
- public static boolean isWindowShowing() {
- return smallWindow != null || bigWindow != null;
- }
- /**
- * 判断小火箭是否准备好发射了。
- *
- * @return 当火箭被发到发射台上返回true,否则返回false。
- */
- public static boolean isReadyToLaunch() {
- if ((smallWindowParams.x > launcherParams.x && smallWindowParams.x
- + smallWindowParams.width < launcherParams.x
- + launcherParams.width)
- && (smallWindowParams.y + smallWindowParams.height > launcherParams.y)) {
- return true;
- }
- return false;
- }
- /**
- * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
- *
- * @param context
- * 必须为应用程序的Context.
- * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
- */
- private static WindowManager getWindowManager(Context context) {
- if (mWindowManager == null) {
- mWindowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- }
- return mWindowManager;
- }
- /**
- * 如果ActivityManager还未创建,则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return ActivityManager的实例,用于获取手机可用内存。
- */
- private static ActivityManager getActivityManager(Context context) {
- if (mActivityManager == null) {
- mActivityManager = (ActivityManager) context
- .getSystemService(Context.ACTIVITY_SERVICE);
- }
- return mActivityManager;
- }
- /**
- * 计算已使用内存的百分比,并返回。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 已使用内存的百分比,以字符串形式返回。
- */
- public static String getUsedPercentValue(Context context) {
- String dir = "/proc/meminfo";
- try {
- FileReader fr = new FileReader(dir);
- BufferedReader br = new BufferedReader(fr, 2048);
- String memoryLine = br.readLine();
- String subMemoryLine = memoryLine.substring(memoryLine
- .indexOf("MemTotal:"));
- br.close();
- long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll(
- "\\D+", ""));
- long availableSize = getAvailableMemory(context) / 1024;
- int percent = (int) ((totalMemorySize - availableSize)
- / (float) totalMemorySize * 100);
- return percent + "%";
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "悬浮窗";
- }
- /**
- * 获取当前可用内存,返回数据以字节为单位。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 当前可用内存。
- */
- private static long getAvailableMemory(Context context) {
- ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
- getActivityManager(context).getMemoryInfo(mi);
- return mi.availMem;
- }
- }
接下来还需要修改FloatWindowSmallView中的代码,当手指拖动悬浮窗的时候要将它变成小火箭,如下所示:
- public class FloatWindowSmallView extends LinearLayout {
- /**
- * 记录小悬浮窗的宽度
- */
- public static int windowViewWidth;
- /**
- * 记录小悬浮窗的高度
- */
- public static int windowViewHeight;
- /**
- * 记录系统状态栏的高度
- */
- private static int statusBarHeight;
- /**
- * 用于更新小悬浮窗的位置
- */
- private WindowManager windowManager;
- /**
- * 小悬浮窗的布局
- */
- private LinearLayout smallWindowLayout;
- /**
- * 小火箭控件
- */
- private ImageView rocketImg;
- /**
- * 小悬浮窗的参数
- */
- private WindowManager.LayoutParams mParams;
- /**
- * 记录当前手指位置在屏幕上的横坐标值
- */
- private float xInScreen;
- /**
- * 记录当前手指位置在屏幕上的纵坐标值
- */
- private float yInScreen;
- /**
- * 记录手指按下时在屏幕上的横坐标的值
- */
- private float xDownInScreen;
- /**
- * 记录手指按下时在屏幕上的纵坐标的值
- */
- private float yDownInScreen;
- /**
- * 记录手指按下时在小悬浮窗的View上的横坐标的值
- */
- private float xInView;
- /**
- * 记录手指按下时在小悬浮窗的View上的纵坐标的值
- */
- private float yInView;
- /**
- * 记录小火箭的宽度
- */
- private int rocketWidth;
- /**
- * 记录小火箭的高度
- */
- private int rocketHeight;
- /**
- * 记录当前手指是否按下
- */
- private boolean isPressed;
- public FloatWindowSmallView(Context context) {
- super(context);
- windowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
- smallWindowLayout = (LinearLayout) findViewById(R.id.small_window_layout);
- windowViewWidth = smallWindowLayout.getLayoutParams().width;
- windowViewHeight = smallWindowLayout.getLayoutParams().height;
- rocketImg = (ImageView) findViewById(R.id.rocket_img);
- rocketWidth = rocketImg.getLayoutParams().width;
- rocketHeight = rocketImg.getLayoutParams().height;
- TextView percentView = (TextView) findViewById(R.id.percent);
- percentView.setText(MyWindowManager.getUsedPercentValue(context));
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- isPressed = true;
- // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
- xInView = event.getX();
- yInView = event.getY();
- xDownInScreen = event.getRawX();
- yDownInScreen = event.getRawY() - getStatusBarHeight();
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- break;
- case MotionEvent.ACTION_MOVE:
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- // 手指移动的时候更新小悬浮窗的状态和位置
- updateViewStatus();
- updateViewPosition();
- break;
- case MotionEvent.ACTION_UP:
- isPressed = false;
- if (MyWindowManager.isReadyToLaunch()) {
- launchRocket();
- } else {
- updateViewStatus();
- // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
- if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
- openBigWindow();
- }
- }
- break;
- default:
- break;
- }
- return true;
- }
- /**
- * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
- *
- * @param params
- * 小悬浮窗的参数
- */
- public void setParams(WindowManager.LayoutParams params) {
- mParams = params;
- }
- /**
- * 用于发射小火箭。
- */
- private void launchRocket() {
- MyWindowManager.removeLauncher(getContext());
- new LaunchTask().execute();
- }
- /**
- * 更新小悬浮窗在屏幕中的位置。
- */
- private void updateViewPosition() {
- mParams.x = (int) (xInScreen - xInView);
- mParams.y = (int) (yInScreen - yInView);
- windowManager.updateViewLayout(this, mParams);
- MyWindowManager.updateLauncher();
- }
- /**
- * 更新View的显示状态,判断是显示悬浮窗还是小火箭。
- */
- private void updateViewStatus() {
- if (isPressed && rocketImg.getVisibility() != View.VISIBLE) {
- mParams.width = rocketWidth;
- mParams.height = rocketHeight;
- windowManager.updateViewLayout(this, mParams);
- smallWindowLayout.setVisibility(View.GONE);
- rocketImg.setVisibility(View.VISIBLE);
- MyWindowManager.createLauncher(getContext());
- } else if (!isPressed) {
- mParams.width = windowViewWidth;
- mParams.height = windowViewHeight;
- windowManager.updateViewLayout(this, mParams);
- smallWindowLayout.setVisibility(View.VISIBLE);
- rocketImg.setVisibility(View.GONE);
- MyWindowManager.removeLauncher(getContext());
- }
- }
- /**
- * 打开大悬浮窗,同时关闭小悬浮窗。
- */
- private void openBigWindow() {
- MyWindowManager.createBigWindow(getContext());
- MyWindowManager.removeSmallWindow(getContext());
- }
- /**
- * 用于获取状态栏的高度。
- *
- * @return 返回状态栏高度的像素值。
- */
- private int getStatusBarHeight() {
- if (statusBarHeight == 0) {
- try {
- Class<?> c = Class.forName("com.android.internal.R$dimen");
- Object o = c.newInstance();
- Field field = c.getField("status_bar_height");
- int x = (Integer) field.get(o);
- statusBarHeight = getResources().getDimensionPixelSize(x);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return statusBarHeight;
- }
- /**
- * 开始执行发射小火箭的任务。
- *
- * @author guolin
- */
- class LaunchTask extends AsyncTask<Void, Void, Void> {
- @Override
- protected Void doInBackground(Void... params) {
- // 在这里对小火箭的位置进行改变,从而产生火箭升空的效果
- while (mParams.y > 0) {
- mParams.y = mParams.y - 10;
- publishProgress();
- try {
- Thread.sleep(8);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
- }
- @Override
- protected void onPostExecute(Void result) {
- // 火箭升空结束后,回归到悬浮窗状态
- updateViewStatus();
- mParams.x = (int) (xDownInScreen - xInView);
- mParams.y = (int) (yDownInScreen - yInView);
- windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
- }
- }
- }
同时,当手指离开屏幕的时候,还会调用MyWindowManager的isReadyToLaunch()方法来判断小火箭是否被拖动到火箭发射台上了,如果为true,就会触发火箭升空的动画效果。火箭升空的动画实现是写在LaunchTask这个任务里的,可以看到,这里会在doInBackground()方法中执行耗时逻辑,将小火箭的纵坐标不断减小,以让它实现上升的效果。当纵坐标减小到0的时候,火箭升空的动画就结束了,然后在onPostExecute()方法中重新将悬浮窗显示出来。
另外,在AndroidManifest.xml文件中记得要声明两个权限,如下所示:
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
- <uses-permission android:name="android.permission.GET_TASKS" />
好了,今天的讲解就到这里,伴随着小火箭的起飞,我今年的最后一篇文章也结束了。
新的一年即将来临,祝愿大家在未来的一年里,无论是工作还是学习,都能像这个小火箭一样,腾飞起来,达到一个新的高度!2014年,我们继续共同努力!
出处:http://blog.csdn.net/guolin_blog/article/details/16919859
今天是2013年的最后一天了,这里首先提前祝大家新年快乐!同时,本篇文章也是我今年的最后一篇文章了,因此我想要让它尽量有点特殊性,比起平时的文章要多一些特色。记得在今年年初的时候,我写的第一篇文章是模仿360手机卫士的桌面悬浮窗效果,那么为了能够首尾呼应,今年的最后一篇文章就同样还是来实现桌面悬浮窗的效果吧,当然效果将会更加高级。
相信用过QQ手机管家的朋友们都会知道它有一个小火箭加速的功能,将小火箭拖动到火箭发射台上发射就会出现一个火箭升空的动画,那么今天我们就来模仿着实现一下这个效果吧。
这次我们将代码的重点放在火箭升空的效果上,因此简单起见,就直接在模仿360手机卫士悬浮窗的那份代码的基础上继续开发了,如果你还没有看过那篇文章的话,建议先去阅读 Android桌面悬浮窗效果实现,仿360手机卫士悬浮窗效果 。
比起普通的桌面悬浮窗,现在我们需要在拖动悬浮窗的时候将悬浮窗变成一个小火箭,并且在屏幕的底部添加一个火箭发射台。那么我们就从火箭发射台开始编写吧,首先创建launcher.xml作为火箭发射台的布局文件,如下所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- >
- <ImageView
- android:id="@+id/launcher_img"
- android:layout_width="200dp"
- android:layout_height="88dp"
- android:src="@drawable/launcher_bg_hold"
- />
- </LinearLayout>
接下来创建RocketLauncher类,作为火箭发射台的View,代码如下所示:
- public class RocketLauncher extends LinearLayout {
- /**
- * 记录火箭发射台的宽度
- */
- public static int width;
- /**
- * 记录火箭发射台的高度
- */
- public static int height;
- /**
- * 火箭发射台的背景图片
- */
- private ImageView launcherImg;
- public RocketLauncher(Context context) {
- super(context);
- LayoutInflater.from(context).inflate(R.layout.launcher, this);
- launcherImg = (ImageView) findViewById(R.id.launcher_img);
- width = launcherImg.getLayoutParams().width;
- height = launcherImg.getLayoutParams().height;
- }
- /**
- * 更新火箭发射台的显示状态。如果小火箭被拖到火箭发射台上,就显示发射。
- */
- public void updateLauncherStatus(boolean isReadyToLaunch) {
- if (isReadyToLaunch) {
- launcherImg.setImageResource(R.drawable.launcher_bg_fire);
- } else {
- launcherImg.setImageResource(R.drawable.launcher_bg_hold);
- }
- }
- }
新增的文件只有这两个,剩下的就是要修改之前的代码了。首先修改MyWindowManager中的代码,如下所示:
- public class MyWindowManager {
- /**
- * 小悬浮窗View的实例
- */
- private static FloatWindowSmallView smallWindow;
- /**
- * 大悬浮窗View的实例
- */
- private static FloatWindowBigView bigWindow;
- /**
- * 火箭发射台的实例
- */
- private static RocketLauncher rocketLauncher;
- /**
- * 小悬浮窗View的参数
- */
- private static LayoutParams smallWindowParams;
- /**
- * 大悬浮窗View的参数
- */
- private static LayoutParams bigWindowParams;
- /**
- * 火箭发射台的参数
- */
- private static LayoutParams launcherParams;
- /**
- * 用于控制在屏幕上添加或移除悬浮窗
- */
- private static WindowManager mWindowManager;
- /**
- * 用于获取手机可用内存
- */
- private static ActivityManager mActivityManager;
- /**
- * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
- */
- public static void createSmallWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (smallWindow == null) {
- smallWindow = new FloatWindowSmallView(context);
- if (smallWindowParams == null) {
- smallWindowParams = new LayoutParams();
- smallWindowParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
- smallWindowParams.format = PixelFormat.RGBA_8888;
- smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
- | LayoutParams.FLAG_NOT_FOCUSABLE;
- smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- smallWindowParams.width = FloatWindowSmallView.windowViewWidth;
- smallWindowParams.height = FloatWindowSmallView.windowViewHeight;
- smallWindowParams.x = screenWidth;
- smallWindowParams.y = screenHeight / 2;
- }
- smallWindow.setParams(smallWindowParams);
- windowManager.addView(smallWindow, smallWindowParams);
- }
- }
- /**
- * 将小悬浮窗从屏幕上移除。
- */
- public static void removeSmallWindow(Context context) {
- if (smallWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(smallWindow);
- smallWindow = null;
- }
- }
- /**
- * 创建一个大悬浮窗。位置为屏幕正中间。
- */
- public static void createBigWindow(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (bigWindow == null) {
- bigWindow = new FloatWindowBigView(context);
- if (bigWindowParams == null) {
- bigWindowParams = new LayoutParams();
- bigWindowParams.x = screenWidth / 2
- - FloatWindowBigView.viewWidth / 2;
- bigWindowParams.y = screenHeight / 2
- - FloatWindowBigView.viewHeight / 2;
- bigWindowParams.type = LayoutParams.TYPE_PHONE;
- bigWindowParams.format = PixelFormat.RGBA_8888;
- bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
- bigWindowParams.width = FloatWindowBigView.viewWidth;
- bigWindowParams.height = FloatWindowBigView.viewHeight;
- }
- windowManager.addView(bigWindow, bigWindowParams);
- }
- }
- /**
- * 将大悬浮窗从屏幕上移除。
- */
- public static void removeBigWindow(Context context) {
- if (bigWindow != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(bigWindow);
- bigWindow = null;
- }
- }
- /**
- * 创建一个火箭发射台,位置为屏幕底部。
- */
- public static void createLauncher(Context context) {
- WindowManager windowManager = getWindowManager(context);
- int screenWidth = windowManager.getDefaultDisplay().getWidth();
- int screenHeight = windowManager.getDefaultDisplay().getHeight();
- if (rocketLauncher == null) {
- rocketLauncher = new RocketLauncher(context);
- if (launcherParams == null) {
- launcherParams = new LayoutParams();
- launcherParams.x = screenWidth / 2 - RocketLauncher.width / 2;
- launcherParams.y = screenHeight - RocketLauncher.height;
- launcherParams.type = LayoutParams.TYPE_PHONE;
- launcherParams.format = PixelFormat.RGBA_8888;
- launcherParams.gravity = Gravity.LEFT | Gravity.TOP;
- launcherParams.width = RocketLauncher.width;
- launcherParams.height = RocketLauncher.height;
- }
- windowManager.addView(rocketLauncher, launcherParams);
- }
- }
- /**
- * 将火箭发射台从屏幕上移除。
- */
- public static void removeLauncher(Context context) {
- if (rocketLauncher != null) {
- WindowManager windowManager = getWindowManager(context);
- windowManager.removeView(rocketLauncher);
- rocketLauncher = null;
- }
- }
- /**
- * 更新火箭发射台的显示状态。
- */
- public static void updateLauncher() {
- if (rocketLauncher != null) {
- rocketLauncher.updateLauncherStatus(isReadyToLaunch());
- }
- }
- /**
- * 更新小悬浮窗的TextView上的数据,显示内存使用的百分比。
- *
- * @param context
- * 可传入应用程序上下文。
- */
- public static void updateUsedPercent(Context context) {
- if (smallWindow != null) {
- TextView percentView = (TextView) smallWindow
- .findViewById(R.id.percent);
- percentView.setText(getUsedPercentValue(context));
- }
- }
- /**
- * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
- *
- * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
- */
- public static boolean isWindowShowing() {
- return smallWindow != null || bigWindow != null;
- }
- /**
- * 判断小火箭是否准备好发射了。
- *
- * @return 当火箭被发到发射台上返回true,否则返回false。
- */
- public static boolean isReadyToLaunch() {
- if ((smallWindowParams.x > launcherParams.x && smallWindowParams.x
- + smallWindowParams.width < launcherParams.x
- + launcherParams.width)
- && (smallWindowParams.y + smallWindowParams.height > launcherParams.y)) {
- return true;
- }
- return false;
- }
- /**
- * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
- *
- * @param context
- * 必须为应用程序的Context.
- * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
- */
- private static WindowManager getWindowManager(Context context) {
- if (mWindowManager == null) {
- mWindowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- }
- return mWindowManager;
- }
- /**
- * 如果ActivityManager还未创建,则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return ActivityManager的实例,用于获取手机可用内存。
- */
- private static ActivityManager getActivityManager(Context context) {
- if (mActivityManager == null) {
- mActivityManager = (ActivityManager) context
- .getSystemService(Context.ACTIVITY_SERVICE);
- }
- return mActivityManager;
- }
- /**
- * 计算已使用内存的百分比,并返回。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 已使用内存的百分比,以字符串形式返回。
- */
- public static String getUsedPercentValue(Context context) {
- String dir = "/proc/meminfo";
- try {
- FileReader fr = new FileReader(dir);
- BufferedReader br = new BufferedReader(fr, 2048);
- String memoryLine = br.readLine();
- String subMemoryLine = memoryLine.substring(memoryLine
- .indexOf("MemTotal:"));
- br.close();
- long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll(
- "\\D+", ""));
- long availableSize = getAvailableMemory(context) / 1024;
- int percent = (int) ((totalMemorySize - availableSize)
- / (float) totalMemorySize * 100);
- return percent + "%";
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "悬浮窗";
- }
- /**
- * 获取当前可用内存,返回数据以字节为单位。
- *
- * @param context
- * 可传入应用程序上下文。
- * @return 当前可用内存。
- */
- private static long getAvailableMemory(Context context) {
- ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
- getActivityManager(context).getMemoryInfo(mi);
- return mi.availMem;
- }
- }
接下来还需要修改FloatWindowSmallView中的代码,当手指拖动悬浮窗的时候要将它变成小火箭,如下所示:
- public class FloatWindowSmallView extends LinearLayout {
- /**
- * 记录小悬浮窗的宽度
- */
- public static int windowViewWidth;
- /**
- * 记录小悬浮窗的高度
- */
- public static int windowViewHeight;
- /**
- * 记录系统状态栏的高度
- */
- private static int statusBarHeight;
- /**
- * 用于更新小悬浮窗的位置
- */
- private WindowManager windowManager;
- /**
- * 小悬浮窗的布局
- */
- private LinearLayout smallWindowLayout;
- /**
- * 小火箭控件
- */
- private ImageView rocketImg;
- /**
- * 小悬浮窗的参数
- */
- private WindowManager.LayoutParams mParams;
- /**
- * 记录当前手指位置在屏幕上的横坐标值
- */
- private float xInScreen;
- /**
- * 记录当前手指位置在屏幕上的纵坐标值
- */
- private float yInScreen;
- /**
- * 记录手指按下时在屏幕上的横坐标的值
- */
- private float xDownInScreen;
- /**
- * 记录手指按下时在屏幕上的纵坐标的值
- */
- private float yDownInScreen;
- /**
- * 记录手指按下时在小悬浮窗的View上的横坐标的值
- */
- private float xInView;
- /**
- * 记录手指按下时在小悬浮窗的View上的纵坐标的值
- */
- private float yInView;
- /**
- * 记录小火箭的宽度
- */
- private int rocketWidth;
- /**
- * 记录小火箭的高度
- */
- private int rocketHeight;
- /**
- * 记录当前手指是否按下
- */
- private boolean isPressed;
- public FloatWindowSmallView(Context context) {
- super(context);
- windowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
- smallWindowLayout = (LinearLayout) findViewById(R.id.small_window_layout);
- windowViewWidth = smallWindowLayout.getLayoutParams().width;
- windowViewHeight = smallWindowLayout.getLayoutParams().height;
- rocketImg = (ImageView) findViewById(R.id.rocket_img);
- rocketWidth = rocketImg.getLayoutParams().width;
- rocketHeight = rocketImg.getLayoutParams().height;
- TextView percentView = (TextView) findViewById(R.id.percent);
- percentView.setText(MyWindowManager.getUsedPercentValue(context));
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- isPressed = true;
- // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
- xInView = event.getX();
- yInView = event.getY();
- xDownInScreen = event.getRawX();
- yDownInScreen = event.getRawY() - getStatusBarHeight();
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- break;
- case MotionEvent.ACTION_MOVE:
- xInScreen = event.getRawX();
- yInScreen = event.getRawY() - getStatusBarHeight();
- // 手指移动的时候更新小悬浮窗的状态和位置
- updateViewStatus();
- updateViewPosition();
- break;
- case MotionEvent.ACTION_UP:
- isPressed = false;
- if (MyWindowManager.isReadyToLaunch()) {
- launchRocket();
- } else {
- updateViewStatus();
- // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
- if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
- openBigWindow();
- }
- }
- break;
- default:
- break;
- }
- return true;
- }
- /**
- * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
- *
- * @param params
- * 小悬浮窗的参数
- */
- public void setParams(WindowManager.LayoutParams params) {
- mParams = params;
- }
- /**
- * 用于发射小火箭。
- */
- private void launchRocket() {
- MyWindowManager.removeLauncher(getContext());
- new LaunchTask().execute();
- }
- /**
- * 更新小悬浮窗在屏幕中的位置。
- */
- private void updateViewPosition() {
- mParams.x = (int) (xInScreen - xInView);
- mParams.y = (int) (yInScreen - yInView);
- windowManager.updateViewLayout(this, mParams);
- MyWindowManager.updateLauncher();
- }
- /**
- * 更新View的显示状态,判断是显示悬浮窗还是小火箭。
- */
- private void updateViewStatus() {
- if (isPressed && rocketImg.getVisibility() != View.VISIBLE) {
- mParams.width = rocketWidth;
- mParams.height = rocketHeight;
- windowManager.updateViewLayout(this, mParams);
- smallWindowLayout.setVisibility(View.GONE);
- rocketImg.setVisibility(View.VISIBLE);
- MyWindowManager.createLauncher(getContext());
- } else if (!isPressed) {
- mParams.width = windowViewWidth;
- mParams.height = windowViewHeight;
- windowManager.updateViewLayout(this, mParams);
- smallWindowLayout.setVisibility(View.VISIBLE);
- rocketImg.setVisibility(View.GONE);
- MyWindowManager.removeLauncher(getContext());
- }
- }
- /**
- * 打开大悬浮窗,同时关闭小悬浮窗。
- */
- private void openBigWindow() {
- MyWindowManager.createBigWindow(getContext());
- MyWindowManager.removeSmallWindow(getContext());
- }
- /**
- * 用于获取状态栏的高度。
- *
- * @return 返回状态栏高度的像素值。
- */
- private int getStatusBarHeight() {
- if (statusBarHeight == 0) {
- try {
- Class<?> c = Class.forName("com.android.internal.R$dimen");
- Object o = c.newInstance();
- Field field = c.getField("status_bar_height");
- int x = (Integer) field.get(o);
- statusBarHeight = getResources().getDimensionPixelSize(x);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return statusBarHeight;
- }
- /**
- * 开始执行发射小火箭的任务。
- *
- * @author guolin
- */
- class LaunchTask extends AsyncTask<Void, Void, Void> {
- @Override
- protected Void doInBackground(Void... params) {
- // 在这里对小火箭的位置进行改变,从而产生火箭升空的效果
- while (mParams.y > 0) {
- mParams.y = mParams.y - 10;
- publishProgress();
- try {
- Thread.sleep(8);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
- }
- @Override
- protected void onPostExecute(Void result) {
- // 火箭升空结束后,回归到悬浮窗状态
- updateViewStatus();
- mParams.x = (int) (xDownInScreen - xInView);
- mParams.y = (int) (yDownInScreen - yInView);
- windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
- }
- }
- }
同时,当手指离开屏幕的时候,还会调用MyWindowManager的isReadyToLaunch()方法来判断小火箭是否被拖动到火箭发射台上了,如果为true,就会触发火箭升空的动画效果。火箭升空的动画实现是写在LaunchTask这个任务里的,可以看到,这里会在doInBackground()方法中执行耗时逻辑,将小火箭的纵坐标不断减小,以让它实现上升的效果。当纵坐标减小到0的时候,火箭升空的动画就结束了,然后在onPostExecute()方法中重新将悬浮窗显示出来。
另外,在AndroidManifest.xml文件中记得要声明两个权限,如下所示:
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
- <uses-permission android:name="android.permission.GET_TASKS" />
好了,今天的讲解就到这里,伴随着小火箭的起飞,我今年的最后一篇文章也结束了。
新的一年即将来临,祝愿大家在未来的一年里,无论是工作还是学习,都能像这个小火箭一样,腾飞起来,达到一个新的高度!2014年,我们继续共同努力!