【问题标题】:How to detect touch events outside the view in background service?如何在后台服务中检测视图之外的触摸事件?
【发布时间】:2020-03-10 11:50:38
【问题描述】:

我试图在后台服务中检测触摸事件,以便在用户使用任何应用程序时获取所有触摸事件。

我所做的是使用 WindowManager 添加一个小视图,当在后台运行应用程序时,这个小视图仍然可以在屏幕上。我还将视图设置为 onTouchListener,因此当用户在视图内触摸时,我可以获得触摸事件。

我的问题是有什么方法可以检测这个小视图之外的触摸事件。

这是我的代码。

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;
}

【问题讨论】:

    标签: java android


    【解决方案1】:

    你不能。出于安全原因,当您不是前台应用程序时,Android 明确不允许您获取触摸事件。您正在尝试做的是明确反对操作系统想要的,如果您找到一种方法,Google 会尽快填补漏洞。做到这一点的唯一方法是在有根设备上,这意味着它无法在 play store 上运行(而实现它的方法是从 linux 设备层读取触摸数据)。

    【讨论】:

    • 好的。我将尝试从 linux 设备层读取触摸数据。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    相关资源
    最近更新 更多