我想在我的应用程序中实现一个浮动窗口函数,它将响应用户输入:
1.当用户点击浮动窗口时,我的应用程序将截取当前显示的屏幕截图并将其保存到/ sdcard目录。在此过程中,浮动窗口应该消失或隐藏一段时间,以便屏幕截图只包含浮动窗口本身以外显示的所有内容。如果用户双击浮动窗口(比如在1000毫秒内点击两次),浮动窗口将被销毁并移除。
2.当用户触摸浮动窗口并在屏幕上移动时,浮动窗口应相应地更新其位置。
我已经尝试了很长时间,我的代码列在下面。问题是我不能让浮动窗口及时消失,因此我拍摄的每个屏幕截图都包含浮动窗口的视图。更有趣的是,有时当我点击两次浮动窗口时,我的应用程序只会截取两次不应该截屏的截图。
有人可以帮我吗?
聚苯乙烯。类本身是一个服务,一旦点击MainActivity中的某个按钮就会触发该服务。
代码:
public class ServiceFloating extends Service {
private WindowManager windowManager;
private WindowManager.LayoutParams paramsF;
private ImageView floatIcon;
long lastPressTime;
private Boolean mHasDoubleClicked;
public RootUtil rootUtil;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
floatIcon = new ImageView(this);
floatIcon.setImageResource(R.drawable.floating);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(floatIcon, params);
try {
floatIcon.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Get current time in nano seconds.
long pressTime = System.currentTimeMillis();
// If double click...(click interval should be longer than 1000)
if (pressTime - lastPressTime <= 1000) {
ServiceFloating.this.stopSelf();
mHasDoubleClicked = true;
} else {
mHasDoubleClicked = false;
}
lastPressTime = pressTime;
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(floatIcon, paramsF);
break;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
floatIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//initiatePopupWindow(floatIcon);
if (!mHasDoubleClicked) {
if (rootUtil == null) {
rootUtil = RootUtil.getInstance();
}
Vibrator vb = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vb.vibrate(100);
String tempFileName = String.valueOf(System.currentTimeMillis());
rootUtil.execute("screencap -p /sdcard/" + tempFileName + ".png");
}
}
});
}
}