Android使用WindowManager實現懸浮窗
阿新 • • 發佈:2019-01-28
上一篇文章Framework學習(十一)WindowManager體系我們分析了WindowManager的用法及原始碼,這篇文章我們使用WindowManager實現一個簡單的懸浮窗效果。
類似與下面這種效果:
專案目錄
專案目錄結構很簡單,一個MainActivity,一個WindowService。MainActivity只有兩個按鈕,用於啟動和關閉WindowService。新增實現懸浮窗的邏輯全部放在WindowService中。
還有兩個xml檔案,一個是MainActivity佈局,只有兩個Button,一個是懸浮窗佈局,只有一個TextView,TextView添加了一個圓形背景。
懸浮窗背景用shape實現,放在drawable資料夾下。
專案程式碼
直接上程式碼吧:
MainActivity
public class MainActivity extends AppCompatActivity {
private Button startService;
private Button stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start);
stopService = (Button) findViewById(R.id.stop);
startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent it = new Intent(MainActivity.this, WindowService.class);
startService(it);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent it = new Intent(MainActivity.this, WindowService.class);
stopService(it);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.hx.wms.MainActivity">
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start service" />
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop service"
android:layout_below="@+id/start"/>
</RelativeLayout>
WindowService
public class WindowService extends Service {
private final String TAG = this.getClass().getSimpleName();
private WindowManager.LayoutParams wmParams;
private WindowManager mWindowManager;
private View mWindowView;
private TextView mPercentTv;
private int mStartX;
private int mStartY;
private int mEndX;
private int mEndY;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
initWindowParams();
initView();
addWindowView2Window();
initClick();
}
private void initWindowParams() {
mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
wmParams = new WindowManager.LayoutParams();
//type
wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
wmParams.format = PixelFormat.TRANSLUCENT;
//flags
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wmParams.gravity = Gravity.LEFT | Gravity.TOP;
wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
private void initView() {
mWindowView = LayoutInflater.from(getApplication()).inflate(R.layout.layout_window, null);
mPercentTv = (TextView) mWindowView.findViewById(R.id.percentTv);
}
private void addWindowView2Window() {
mWindowManager.addView(mWindowView, wmParams);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWindowView != null) {
//移除懸浮視窗
Log.i(TAG, "removeView");
mWindowManager.removeView(mWindowView);
}
Log.i(TAG, "onDestroy");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
...
}
在設定各種屬性之後,直接向WindowManager中新增mWindowView(也就是我們自己的佈局layout_window.xml)。
下面我們實現懸浮窗點選和跟著手指拖動的效果,根據拖動距離,判斷是點選還是滑動。由於onTouchEvent()的優先順序比onClick高,拖動時在需要的攔截的地方,return true就行了。具體如下:
private void initClick() {
mPercentTv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartX = (int) event.getRawX();
mStartY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
mEndX = (int) event.getRawX();
mEndY = (int) event.getRawY();
if (needIntercept()) {
//getRawX是觸控位置相對於螢幕的座標,getX是相對於按鈕的座標
wmParams.x = (int) event.getRawX() - mWindowView.getMeasuredWidth() / 2;
wmParams.y = (int) event.getRawY() - mWindowView.getMeasuredHeight() / 2;
mWindowManager.updateViewLayout(mWindowView, wmParams);
return true;
}
break;
case MotionEvent.ACTION_UP:
if (needIntercept()) {
return true;
}
break;
default:
break;
}
return false;
}
});
mPercentTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isAppAtBackground(WindowService.this)) {
Intent intent = new Intent(WindowService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
});
}
/**
* 是否攔截
* @return true:攔截;false:不攔截.
*/
private boolean needIntercept() {
if (Math.abs(mStartX - mEndX) > 30 || Math.abs(mStartY - mEndY) > 30) {
return true;
}
return false;
}
/**
*判斷當前應用程式處於前臺還是後臺
*/
private boolean isAppAtBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
最後需要在AndroidManifest.xml中註冊Service和新增相應的限權。
<service android:name=".WindowService"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.GET_TASKS" />