当前位置:首页 > 开发 > 移动开发 > 正文

悬浮窗

发表于: 2012-05-28   作者:dai_lm   来源:转载   浏览:
摘要: 类似于360监视网络速度的那个悬浮窗 public class FloatWindowService extends Service { WindowManager wm = null; WindowManager.LayoutParams wmParams = null; View view; private float mTouchStartX;
类似于360监视网络速度的那个悬浮窗

public class FloatWindowService extends Service {

	WindowManager wm = null;

	WindowManager.LayoutParams wmParams = null;

	View view;

	private float mTouchStartX;
	private float mTouchStartY;

	private float x;
	private float y;

	@Override
	public void onCreate() {

		super.onCreate();
		setForeground(true);
		view = LayoutInflater.from(this).inflate(R.layout.float_window, null);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		createView();
	}

	private void createView() {
		wm = (WindowManager) getApplicationContext().getSystemService("window");

		wmParams = new WindowManager.LayoutParams();
		wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
		wmParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;

		wmParams.x = 0;
		wmParams.y = 0;

		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.format = PixelFormat.RGBA_8888;

		wm.addView(view, wmParams);

		view.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {

				x = event.getRawX();
				y = event.getRawY();

				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:
					mTouchStartX = event.getX();
					mTouchStartY = event.getY() + view.getHeight() / 2;
					break;

				case MotionEvent.ACTION_MOVE:
					updateViewPosition();
					break;

				case MotionEvent.ACTION_UP:
					updateViewPosition();
					mTouchStartX = mTouchStartY = 0;
					break;
				}

				return true;
			}
		});
	}

	private void updateViewPosition() {

		wmParams.x = (int) (x - mTouchStartX);
		wmParams.y = (int) (y - mTouchStartY);
		wm.updateViewLayout(view, wmParams);
	}

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


悬浮窗的layout就请自行添加了,click事件只要注册一下onClickListener就可以了

注意
1. 必须在AndroidManifest.xml里添加permission
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />


2. 由于这个悬浮窗实质上是一个Service,所以也必须声明
<service
    android:name="FloatWindowService"
    android:enabled="true" />

悬浮窗

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号