Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

仿 360 加速球實作:Android 懸浮窗與內存釋放全解析

編輯:Android 省電與效能提升

如今手機上的懸浮窗應用越來越多,對使用者來說,最常見的就是安全軟件的懸浮小控件。以 360 衛士為例,開啟懸浮窗後是一個小球,小球可以拖動,點擊小球會出現大窗體控件,進一步操作如釋放手機內存等。於是趁著慕課網的視頻,我仿著實現了一個 360 加速球,並加入了點擊小球釋放內存的功能。

由於只有手機屏幕截圖,先來看看實現效果:點擊開啟按鈕,出現懸浮窗小球,上面顯示手機可用內存百分比;拖動小球時,小球變為 Android 圖標;鬆開後小球依附在屏幕兩側;點擊小球,底部出現大窗體控件,點擊裡面的小球即可釋放內存;點擊屏幕其他區域,大窗體消失,小球重新出現。

效果如下:

1. FloatCircleView 的實現(自定義 View)

實現 FloatCircleView 的過程就是自定義 View 的過程:1、自定義 View 的屬性;2、在構造方法中獲取自定義屬性;3、重寫 onMeasure;4、重寫 onDraw。因為沒自定義額外屬性,省了不少步驟。

首先是各變量初始化,設置拖動時要顯示的圖標,以及計算各種內存(用於顯示在小球上):

 public int width=100; public int heigth=100; private Paint circlePaint;//畫圓 private Paint textPaint; //畫字 private float availMemory; //已用內存 private float totalMemory; //總內存 private String text; //顯示的已用內存百分比 private boolean isDraging=false; //是否在拖動狀態。 private Bitmap src; private Bitmap scaledBitmap; //縮放後的圖片。 /** * 初始化畫筆以及計算可用內存,總內存,和可用內存百分比。 */ public void initPatints() { circlePaint = new Paint(); circlePaint.setColor(Color.CYAN); circlePaint.setAntiAlias(true); textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTextSize(25); textPaint.setFakeBoldText(true); textPaint.setAntiAlias(true); //設置圖片 src = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); //縮放後的圖片(將圖標設置的和懸浮小球一樣大小。) scaledBitmap = Bitmap.createScaledBitmap(src, width, heigth, true); //計算已用內存,總內存,已用內存百分比, availMemory= (float) getAvailMemory(getContext()); totalMemory= (float) getTotalMemory(getContext()); text=(int)((availMemory/totalMemory)*100)+"%"; } 

onMeasure 就是把固定寬高寫死,通過 setMeasuredDimension(width, heigth) 傳入。onDraw 則進行懸浮小球繪制:定義一個 boolean 變量判斷是否為拖動狀態,若是就繪制 Android 圖標,否則繪制小球。畫小球沒難度,關鍵是畫字——下面兩張圖能加深理解。

1. 畫字時的 x 坐標:先用 textPaint.measureText(text) 得到字的寬度,再用小球寬度/2 減字寬/2。
2. 畫字時的 y 坐標:先用 Paint.FontMetrics 得到字體測量類,再用 (fontMetrics.ascent + fontMetrics.descent) / 2 得到字高,最後用小球高度/2 減字高/2。

畫個圖就很好理解了:

 /** * 畫小球及文字。如果小球是在拖動狀態就顯示android圖標,如果不是拖動狀態就顯示小球。 * @param canvas */ @Override protected void onDraw(Canvas canvas) { if (isDraging){ canvas.drawBitmap(scaledBitmap,0,0,null); }else { //1.畫圓 canvas.drawCircle(width / 2, heigth / 2, width / 2, circlePaint); //2.畫text float textwidth = textPaint.measureText(text);//文本寬度 float x = width / 2 - textwidth / 2; Paint.FontMetrics fontMetrics = textPaint.getFontMetrics(); float dy = -(fontMetrics.ascent + fontMetrics.descent) / 2; float y = heigth / 2 + dy; canvas.drawText(text, x, y, textPaint); } } 

獲得手機已用內存及總內存的方法:

 public long getAvailMemory(Context context) { // 獲取android當前可用內存大小 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); am.getMemoryInfo(mi); //mi.availMem; 當前系統的可用內存 //return Formatter.formatFileSize(context, mi.availMem);// 將獲取的內存大小規格化 return mi.availMem/(1024*1024); } public long getTotalMemory(Context context) { String str1 = "/proc/meminfo";// 系統內存信息文件 String str2; String[] arrayOfString; long initial_memory = 0; try { FileReader localFileReader = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader( localFileReader, 8192); str2 = localBufferedReader.readLine();// 讀取meminfo第一行,系統總內存大小 arrayOfString = str2.split("\\s+"); for (String num : arrayOfString) { Log.i(str2, num + "\t"); } initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 獲得系統總內存,單位是KB,乘以1024轉換為Byte localBufferedReader.close(); } catch (IOException e) { } //return Formatter.formatFileSize(context, initial_memory);// Byte轉換為KB或者MB,內存大小規格化 return initial_memory/(1024*1024); } 

2. 創建 WindowManager 管理懸浮小球與底部窗體

WindowManager 用來管理整個懸浮小球和手機底部大窗體的顯示與隱藏。必須在 Manifest 中增加 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 權限。透過 getSystemService(Context.WINDOW_SERVICE) 獲取窗體管理類;用 wm.addView(view, params) 增加 view;用 wm.remove(view, params) 移除 view;用 wm.updateViewLayout(view, params) 更新 view。WindowManager.LayoutParams 則用來設置 view 的各種屬性。

1. 以單例模式創建 FloatViewManager 實例:

 //單例模式創建 public static FloatViewManager getInstance(Context context){ if (inStance==null){ synchronized(FloatViewManager.class){ if (inStance==null){ inStance=new FloatViewManager(context); } } } return inStance; } 

2. 展示懸浮小球和底部窗體的方法:

 /** * 展示浮窗 */ public void showFloatCircleView(){ //參數設置 if (params==null){ params = new WindowManager.LayoutParams(); //寬高 params.width=circleView.width; params.height=circleView.heigth; //對齊方式 params.gravity= Gravity.TOP|Gravity.LEFT; //偏移量 params.x=0; params.y=0; //類型 params.type=WindowManager.LayoutParams.TYPE_TOAST; //設置該window屬性。 params.flags= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; //像素格式 params.format= PixelFormat.RGBA_8888; } //將小球加入窗體中。 wm.addView(circleView, params); } public void showFloatCircleView(){ ...... } 

3. 啟動程序時先創建懸浮小球,小球可拖拽,點擊後底部窗體(FloatMenuView)顯示、小球隱藏。因此要對 circleView 設置 setOnTouchListener 和 setOnClickListener 監聽。

小球的事件分發分析:ACTION_DOWN 時記錄 downX、downY 及 startX、startY;ACTION_MOVE 時將小球拖拽狀態置為 true,記錄 moveX、moveY,算出移動距離 dx、dy,再用 wm.updateViewLayout 更新位置,最後把 move 坐標賦值給 startX、startY;ACTION_UP 時將拖拽狀態置 false,根據 upx 與屏幕寬度/2 的比較判斷小球最終貼左側還是右側。當拖拽距離小於 10 像素時觸發點擊事件(Touch 事件返回 true 則消費、不再下傳;返回 false 則繼續下傳並觸發點擊)。

小球的點擊事件:點擊後懸浮小球隱藏、底部窗體出現,並帶入場過渡動畫。

 //給circleView設置touch監聽。 private View.OnTouchListener circleViewOnTouchListener=new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //最後按下時的坐標,根據ACTION_MOVE理解。 startX = event.getRawX(); startY = event.getRawY(); //按下時的坐標。 downX = event.getRawX(); downY = event.getRawY(); break; case MotionEvent.ACTION_MOVE: circleView.setDrageState(true); moveX = event.getRawX(); moveY=event.getRawY(); float dx = moveX -startX; float dy=moveY-startY; params.x+=dx; params.y+=dy; wm.updateViewLayout(circleView,params); startX= moveX; startY=moveY; break; case MotionEvent.ACTION_UP: float upx=event.getRawX(); if (upx>getScreenWidth()/2){ params.x=getScreenWidth()-circleView.width; }else { params.x=0; } circleView.setDrageState(false); wm.updateViewLayout(circleView,params); if (Math.abs(moveX-downX)>10){ return true; }else { return false; } default: break; } return false; } }; circleView.setOnTouchListener(circleViewOnTouchListener); circleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(, "onclick", Toast.LENGTH_SHORT).show(); //隱藏circleView,顯示菜單欄。 wm.removeView(circleView); showFloatMenuView(); floatMenuView.startAnimation(); } }); 

3. MyProgreeView(底部窗體中小球的實現)

1. 初始化畫筆並對 view 進行手勢監聽,監聽單擊與雙擊事件(必須設置 view 可點擊):

 private void initPaint() { //畫圓畫筆 circlepaint = new Paint(); circlepaint.setColor(Color.argb(0xff, 0x3a, 0x8c, 0x6c)); circlepaint.setAntiAlias(true); //畫進度條畫筆 progerssPaint = new Paint(); progerssPaint.setAntiAlias(true); progerssPaint.setColor(Color.argb(0xff, 0x4e, 0xcc, 0x66)); progerssPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//繪制重疊部分 //畫進度畫筆 textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setColor(Color.WHITE); textPaint.setTextSize(25); //畫布 bitmap = Bitmap.createBitmap(width, heigth, Bitmap.Config.ARGB_8888); bitmapCanvas = new Canvas(bitmap); //手勢監聽。 gestureDetector = new GestureDetector(new MyGertureDetectorListener()); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); //設置view可以點擊。 setClickable(true); } class MyGertureDetectorListener extends GestureDetector.SimpleOnGestureListener{ @Override public boolean onDoubleTap(MotionEvent e) { ...... //雙擊事件的邏輯 return super.onDoubleTap(e); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { ...... //單擊事件的邏輯 return super.onSingleTapConfirmed(e); } } 

2. 用 handler 週期交互更新單擊與雙擊狀態。單擊時利用貝塞爾曲線實現波紋蕩漾;雙擊時波紋不斷下降、進行內存釋放,最後顯示釋放後的已用內存百分比。handler 發送週期消息讓小球不斷重繪:

 //單擊事件發送周期handler. private void startSingleTapAnimation() { handler.postDelayed(singleTapRunnable,200); } private SingleTapRunnable singleTapRunnable=new SingleTapRunnable(); class SingleTapRunnable implements Runnable{ @Override public void run() { count--; if (count>=0) { invalidate();//不斷進行重繪。 handler.postDelayed(singleTapRunnable,200); }else { handler.removeCallbacks(singleTapRunnable); count=50; } } } //雙擊事件發送周期handler。 private void startDoubleTapAnimation() { handler.postDelayed(runnbale,50); } private DoubleTapRunnable runnbale=new DoubleTapRunnable(); class DoubleTapRunnable implements Runnable{ @Override public void run() { num--; if (num>=0){ invalidate();//不斷進行重繪。 handler.postDelayed(runnbale,50); }else { handler.removeCallbacks(runnbale); //釋放內存。 killprocess(); //計算釋放後的已用內存百分比。 num=(int)(((float)currentProgress/max)*100); } } } 

3. 單擊與雙擊的重繪。先繪制小球與波紋路徑,每次繪制前把上次的 path reset:

 //繪制小球 bitmapCanvas.drawCircle(width / 2, heigth / 2, width / 2, circlepaint); //根據path,繪制波紋路徑。每次繪制前將上次的path,reset. path.reset(); float y =(1-(float)num/100)*heigth; path.moveTo(width, y); path.lineTo(width, heigth); path.lineTo(0, heigth); path.lineTo(0, y); 

接著利用貝塞爾曲線繪製波紋。主要用 path.rQuadTo(x1, y1, x2, y2)(終點 x2,y2,輔助控制點 x1,y1),只要不斷改變 y1 的位置,就能畫出水波紋效果。先判斷是否為雙擊:若是雙擊,用變量 d(由 handler 中不斷遞減的 num 引起)控制曲線起伏,實現水波下降;若是單擊,用 count 值控制,判斷 count 能否被 2 整除,交替繪制兩條相反的貝塞爾曲線,實現水波蕩漾。用 for 循環實現多道波紋(一對 rQuadTo 只能畫一次波紋)。

 if (!isSingleTap){ float d=(1-(float)num/(100/2))*10; for (int i=0;i<3;i++){ path.rQuadTo(10,-d,20,0); path.rQuadTo(10,d,20,0); } }else { float d=(float)count/50*10; if (count%2==0){ for (int i=0;i<=3;i++){ path.rQuadTo(10,-d,30,0); path.rQuadTo(10,d,30,0); } }else { for (int i=0;i<=3;i++){ path.rQuadTo(10,d,30,0); path.rQuadTo(10,-d,30,0); } } } 

最後是釋放內存的方法,記得在 Manifest 增加 <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/> 權限:

 public void killprocess(){ ActivityManager activityManger=(ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> list=activityManger.getRunningAppProcesses(); if(list!=null) for(int i=0;i<list.size();i++) { ActivityManager.RunningAppProcessInfo apinfo=list.get(i); String[] pkgList=apinfo.pkgList; if(apinfo.importance>ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) { // Process.killProcess(apinfo.pid); for(int j=0;j<pkgList.length;j++) { boolean flag=pkgList[j].contains("com.example.yyh.animation360");//這裡要判斷是否為當前應用,要不然也可能會結束當前應用。 if(!flag){ activityManger.killBackgroundProcesses(pkgList[j]); } } } }

4. FloatMenuView 的實現

1. 創建 float_menuview.xml,包含一個 ImageView + TextView + 自定義的 MyProgreeView,底部窗體要設置 android:clickable="true":

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#33000000" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#F02F3942" android:layout_alignParentBottom="true" android:id="@+id/ll" android:clickable="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@mipmap/ic_launcher" android:layout_gravity="center_vertical" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" android:textColor="#c93944" android:text="360加速球" android:layout_gravity="center_vertical" /> </LinearLayout> <com.example.yyh.animation360.view.MyProgreeView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" /> </LinearLayout> </RelativeLayout> 

2. 依條件用 wm.addView / wm.remove 控制底部窗體的顯示與隱藏。用 TranslateAnimation 設置底部窗體的入場動畫。TranslateAnimation 的參數中,参照值有三種:Animation.ABSOLUTE(絕對屏幕像素)、Animation.RELATIVE_TO_SELF(相對自己)、Animation.RELATIVE_TO_PARENT(相對父容器),每個參數後一個為前一參數類型的起始值。

同時對該 view 設置 OnTouchListener,onTouch 事件最後必須返回 false,表示事件仍需向下傳遞。如此便能實現:點擊屏幕其他區域時底部窗體隱藏、懸浮小球顯示;點擊底部窗體時無變化;點擊窗體中的小球時觸發其單擊與雙擊事件。

 View view =View.inflate(getContext(), R.layout.float_menuview,null); LinearLayout linearLayout= (LinearLayout) view.findViewById(R.id.ll); translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,1.0f,Animation.RELATIVE_TO_SELF,0); translateAnimation.setDuration(500); translateAnimation.setFillAfter(true); linearLayout.setAnimation(translateAnimation); view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { FloatViewManager manager=FloatViewManager.getInstance(getContext()); manager.hideFloatMenuView(); manager.showFloatCircleView(); return false; } }); addView(view); 

5. MyFloatService

用來創建 FloatViewManager 單例,管理懸浮小球與底部窗體的建立和移除:

 public class MyFloatService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { //用來開啟FloatViewManager FloatViewManager manager=FloatViewManager.getInstance(this); manager.showFloatCircleView(); super.onCreate(); } } 

6. MainActivity 的實現

定義一個 intent 開啟服務(服務中創建 WindowManager 單例進行管理),並關閉當前 activity:

 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View view){ Intent intent=new Intent(this, MyFloatService.class); startService(intent); finish(); } } 

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved