使用Service來顯示懸浮窗且可移動在視窗上面的方法如下:
再AndroidManifest.xml寫入權限:
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_PERMISSION" />
Java語法如下:
public class A1 extends Service {
WindowManager wm;
WindowManager.LayoutParams wmParams
WindowManager.LayoutParams wmParams
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int fags, int startId) {
bc = new ImageButton(this);//顯示的物件
wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//斷判API版本選擇 WindowManager.LayoutParams的元件
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;
}
wmParams = new WindowManager.LayoutParams(150, 150, LAYOUT_FLAG,
WindowManager.LayoutParams.FIRST_SUB_WINDOW,
PixelFormat.TRANSLUCENT);
wm.addView(bc, wmParams);//新增方法
//以下為ImageButton移動的方法
bc.setOnTouchListener(new View.OnTouchListener() {
boolean k_click=false;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
bc.setOnTouchListener(new View.OnTouchListener() {
boolean k_click=false;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x0 = event.getRawX();
y0 = event.getRawY();
case MotionEvent.ACTION_MOVE:
y0 = event.getRawY();
case MotionEvent.ACTION_MOVE:
mx0 = event.getRawX();
my0 = event.getRawY();
wmParams.x += (mx0 - x0);
wmParams.y += (my0 - y0);
case MotionEvent.ACTION_UP:
x0 = mx0;
y0 = my0;
my0 = event.getRawY();
wmParams.x += (mx0 - x0);
wmParams.y += (my0 - y0);
case MotionEvent.ACTION_UP:
x0 = mx0;
y0 = my0;
}
wm.updateViewLayout(v, wmParams);//更新的方法
Log.i("bc移動:", mx0 + "~" + my0);
return true;
}
Log.i("bc移動:", mx0 + "~" + my0);
return true;
}
});
}
@Override
public void onDestroy() {
wm.removeView(bc);//移除的方法
//關閉Service時執行
super.onDestroy();
}
}
public void onDestroy() {
wm.removeView(bc);//移除的方法
//關閉Service時執行
super.onDestroy();
}
}
大大您好
回覆刪除bc = new ImageButton(this);//顯示的物件
這行無法宣告 是要在介面上面拉一個 ImageButton嗎?