Android浮動視窗的實現

來源:互聯網
上載者:User

標籤:android   style   blog   http   os   io   使用   ar   for   

1.浮動視窗的實現原理

看到的那個小Android表徵圖了吧,它不會被其他組建遮擋,也可以響應使用者的點擊和拖動事件,它的顯示和消失由WindowManager直接管理,它就是Android浮動視窗。Android浮動視窗的實現主要是靠WindowManager這個類。通過WindowManager類的addView(),updateViewLayout(),removeView()這幾個方法,我們可以直接在Window中添加,更新,移除View。

2.浮動視窗實現的具體步驟

1)既然浮動視窗的實現依賴與WindowManager,那麼毫無疑問,我們得先拿到WindowManger對象。考慮到浮動視窗通常在應用程式退出後依然顯示,所以我們需要在Service中實現浮動視窗的添加和更新,當然別忘了提供給使用者一個取消浮動視窗的功能。
2)定義你要顯示的View。可以在布局檔案中定義,也可以自訂視圖。
3)設定必要的參數,其中有幾個比較重要的參數需要設定,具體請參考下面的代碼。
4)將View添加到Window中,接收並處理事件,更新View。

5)在Manifest中加入對應的許可權。<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

3.浮動視窗實現代碼

 package com.spreadst.floatwindow;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.graphics.PixelFormat;
 import android.os.IBinder;
 import android.util.Log;
 import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.WindowManager;

 public class FloatWindowService extends Service {

    private static final TAG = "FloatWindowService";

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mLayoutParams;
    private LayoutInflater mLayoutInflater;
    private View mFloatView;
    private int mCurrentX;
    private int mCurrentY;
    private static int mFloatViewWidth = 50;
    private static int mFloatViewHeight = 80;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        //初始化WindowManager對象和LayoutInflater對象
        mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        mLayoutInflater = LayoutInflater.from(this);
    }
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.i(TAG, "onStart()");
        createView();
    }
    private void createView() {
        // TODO Auto-generated method stub
        //載入布局檔案
        mFloatView = mLayoutInflater.inflate(R.layout.main, null);
        //為View設定監聽,以便處理使用者的點擊和拖動
        mFloatView.setOnTouchListener(new OnFloatViewTouchListener());
        /*為View設定參數*/
        mLayoutParams = new WindowManager.LayoutParams();
        //設定View預設的擺放位置
        mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        //設定window type
        mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //設定背景為透明
        mLayoutParams.format = PixelFormat.RGBA_8888;
        //注意該屬性的設定很重要,FLAG_NOT_FOCUSABLE使浮動視窗不擷取焦點,若不設定該屬性,螢幕的其它位置點擊無效,應為它們無法擷取焦點
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //設定視圖的顯示位置,通過WindowManager更新視圖的位置其實就是改變(x,y)的值
        mCurrentX = mLayoutParams.x = 50;
        mCurrentY = mLayoutParams.y = 50;
        //設定視圖的寬、高
        mLayoutParams.width = 100;
        mLayoutParams.height = 100;
        //將視圖添加到Window中
        mWindowManager.addView(mFloatView, mLayoutParams);
    }
    /*由於直接startService(),因此該方法沒用*/
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    /*該方法用來更新視圖的位置,其實就是改變(LayoutParams.x,LayoutParams.y)的值*/
    private void updateFloatView() {
        mLayoutParams.x = mCurrentX;
        mLayoutParams.y = mCurrentY;
        mWindowManager.updateViewLayout(mFloatView, mLayoutParams);
    }
    /*處理視圖的拖動,這裡只對Move事件做了處理,使用者也可以對點擊事件做處理,例如:點擊浮動視窗時,啟動應用的主Activity*/
    private class OnFloatViewTouchListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            Log.i(TAG, "mCurrentX: " + mCurrentX + ",mCurrentY: "
                    + mCurrentY + ",mFloatViewWidth: " + mFloatViewWidth
                    + ",mFloatViewHeight: " + mFloatViewHeight);
            /*
             * getRawX(),getRawY()這兩個方法很重要。通常情況下,我們使用的是getX(),getY()來獲得事件的觸發點座標,
             * 但getX(),getY()獲得的是事件觸發點相對與視圖左上方的座標;而getRawX(),getRawY()獲得的是事件觸發點
             * 相對與螢幕左上方的座標。由於LayoutParams中的x,y是相對與螢幕的,所以需要使用getRawX(),getRawY()。
             */
            mCurrentX = (int) event.getRawX() - mFloatViewWidth;
            mCurrentY = (int) event.getRawY() - mFloatViewHeight;
            int action = event.getAction();
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                updateFloatView();
                break;
            case MotionEvent.ACTION_UP:
                break;
            }
            return true;
        }
    }
 }

4.如何只在Launcher介面顯示浮動視窗

大家應該都熟悉360安全衛士的浮動視窗,它的浮動視窗只會在Launcher介面顯示,當使用者切到其它介面,浮動視窗自動被移除了。
要實現該功能,我們就必須知道當前所在的介面,如果只去監聽Activity的category,那麼我們只能知道什麼時候進入Launcher介面了,卻無法知道是否離開了Launcher介面。那麼360是如何?該功能呢?大家可以反編譯一下它的代碼。這裡提供一種可行的方法,我們的目前其實很簡單,就是要知道當前的Activity是否是Launcher介面的Activity。由於Activity是以堆棧的形式被管理的,因此,只要我們查看棧頂的Activity是否是Launcher的Activity即可。要擷取Activity的Task資訊,需要在Manifest中添加對應許可權,<uses-permission android:name = “android.permission.GET_TASKS”/>。
 private String getTopActivity(Context context) {
     //擷取ActivityManager對象
     ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE) ;
     /*
      * 拿到當前正在啟動並執行Task列表,該列表按照最近使用的時間順序排列,其中的參數表示需要返回的最大清單項目數目。
      * 這裡我們只需要拿到處於onResume狀態的Activity所在的Task。
      */
     List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1) ;
     if(runningTaskInfos != null) {
         //拿到該task中的棧頂Activity
         return (runningTaskInfos.get(0).topActivity).toString() ;
     } else {
         return null;
     }
 }

http://blog.csdn.net/missliang/article/details/8973707

Android浮動視窗的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.