如何在使用Android服务的视图上实现onTouch侦听器?

时间:2018-07-13 17:53:22

标签: android service

即使在关闭我的应用程序后,我仍试图使HUD始终显示在屏幕上。我正在使用服务来制作此HUD。我可以在屏幕上显示文本,但由于某些原因,触摸事件似乎没有被注册。我尝试将OnClickListener,onLongClickListener和onTouchListener设置为视图,但是它不起作用。这是我的代码:

public class HUD extends Service{

// == attributes ==
private HUDView mView;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    mView = new HUDView(this);

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
    );
    params.gravity = Gravity.RIGHT | Gravity.TOP;
    params.setTitle("Load average");

    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.addView(mView, params);

    Toast.makeText(getApplicationContext(), "Service created", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mView != null){
        ((WindowManager)getSystemService(WINDOW_SERVICE)).removeView(mView);
        mView = null;
    }
    Toast.makeText(getApplicationContext(), "Service destroyed", Toast.LENGTH_LONG).show();
}
}

public class HUDView extends View {

// == attributes ==
private Paint mLoadPaint;

// == constructor ==
public HUDView(Context context){
    super(context);

    mLoadPaint = new Paint();
    mLoadPaint.setAntiAlias(true);
    mLoadPaint.setTextSize(30f);
    mLoadPaint.setARGB(255, 255, 255, 0);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawText("hello world width = " + getWidth() + " height = " + getHeight() + " "+ hasOnClickListeners(),50, 250, mLoadPaint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Toast.makeText(getContext(), "onTouch", Toast.LENGTH_SHORT).show();
    System.out.print("onTouch");
    return true;
}
}

0 个答案:

没有答案
相关问题