我目前正在尝试通过包含单个ImageView的X和Y布局连续更新浮动窗口小部件的位置。从主要活动中,我有:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
CursorService.moveCursor(centerX,centerY);
}
},1000
);
上面的代码向(moveCursor)发送信号,该信号试图在CursorService.java包含的浮动叠加层上移动imageview。
centerX和centerY是正确传递的外部变量。
我的问题是试图在CursorService.java类(该类包含整个屏幕上浮动的类似于窗口小部件的覆盖物的类)中实现一个方法。我想每秒更改此光标在覆盖物上的位置,该方法正在调用Mainactivity.java。
以下是CursorService的代码:
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class CursorService extends Service {
private WindowManager mWindowManager;
private static View mFloatingView;
private static ImageView cursor;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
//Inflate the floating view layout we created
mFloatingView = LayoutInflater.from(this).inflate(R.layout.cursor_layout,null);
int LAYOUT_flaG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_flaG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_flaG = WindowManager.LayoutParams.TYPE_PHONE;
}
//Add the view to the window.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT,LAYOUT_flaG,WindowManager.LayoutParams.flaG_NOT_FOCUSABLE,PixelFormat.TRANSLUCENT);
//Specify the view position
params.gravity = Gravity.TOP | Gravity.LEFT; //Initially view will be added to top-left corner
params.x = 0;
params.y = 100;
//Add the view to the window
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView,params);
cursor = mFloatingView.findViewById(R.id.cursor);
}
// Handling the movement
public static void moveCursor(Integer paramX,Integer paramY) {
/******** Implement changing the x and y position of the cursor here ********/
}
@Override
public void onDestroy() {
super.onDestroy();
if (mFloatingView != null) mWindowManager.removeView(mFloatingView);
}
}
我尝试在无限循环中直接更改oncreate方法中的参数,以及从onCreate外部的函数调用中更改X和Y,但是没有运气。对于在浮动叠加层中移动imageview的任何指导,我将不胜感激。
谢谢!