我试图检测后台服务中的触摸事件,以便我可以在用户使用任何应用程序时获取所有触摸事件。
我所做的是使用 WindowManager 添加一个小 View ,当在后台运行应用程序时,这个小 View 仍然可以在屏幕上。我还将 View 设置为 onTouchListener,以便当用户触摸 View 内时,我可以获得触摸事件。
我的问题是有没有办法检测这个小 View 之外的触摸事件。
这是我的代码。
public class GlobalTouchService extends Service implements View.OnTouchListener {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private MyView myView;
private boolean flag = true;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.x = 0;
mLayoutParams.y = 0;
mLayoutParams.height = 300;
mLayoutParams.width = 300;
myView = new MyView(this);
myView.setOnTouchListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (flag) {
flag = false;
mWindowManager.addView(myView, mLayoutParams);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getRawX();
float y = motionEvent.getRawY();
Log.d("x,y", "X" + x + " Y" + y);
return false;
}
最佳答案
你不能。出于安全原因,Android 明确不允许您在非前台应用程序时获取触摸事件。你想要做的事情是明确反对操作系统想要的,如果你找到一种方法,谷歌会尽快堵住你发现的漏洞。执行此操作的唯一方法是在 root 设备上,这意味着它无法在 Play 商店上运行(并且执行此操作的方法是从 Linux 设备层读取触摸数据)。
关于java - 如何在后台服务中检测 View 之外的触摸事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610673/