我想创建一个由服务运行的系统覆盖,以拾取鼠标移动。但我无法拾取触摸/鼠标点。有人可以告诉我这段代码有什么问题。
我可以使用相同的代码从活动中获取鼠标移动,但不能从具有系统覆盖的服务中获取鼠标移动。
使用以下代码从MainActivity运行HUD:
private OnClickListener btnHUDListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(MainActivity.this, HUD.class));
}
};
以下是服务类:
package com.btc.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
public class HUD extends Service {
HUDView mView;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
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);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_LONG).show();
if(mView != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
mView = null;
}
}
}
class HUDView extends ViewGroup {
private Paint mLoadPaint;
public HUDView(Context context) {
super(context);
Toast.makeText(getContext(),"HUDView", Toast.LENGTH_LONG).show();
mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
mLoadPaint.setTextSize(10);
mLoadPaint.setARGB(255, 255, 0, 0);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("Hello World", 5, 15, mLoadPaint);
}
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//return super.onTouchEvent(event);
Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
int action = event.getAction();
MyService.currentXPosition = event.getX();
MyService.currentYPosition = event.getY();
Log.v("A MotionEvent", "Action = " + action);
Log.v("A MotionEvent", "X = " + MyService.currentXPosition + "Y = " + MyService.currentYPosition);
if (action == MotionEvent.ACTION_MOVE) {
// do something
}
if (action == MotionEvent.ACTION_UP) {
// do something
}
//Toast.makeText(null,"onTouchEvent", Toast.LENGTH_LONG).show();
return true;
}
}