Android 悬浮窗口

package com.home.floatwindow;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.home.testfolatwindow.R;

public class FloatService extends Service {

	private WindowManager wm;
	private WindowManager.LayoutParams wmlp;
	private LinearLayout layout;

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

	@Override
	public void onCreate() {
		super.onCreate();
		createFloatView();
	}

	private void createFloatView() {
		wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		wmlp = new WindowManager.LayoutParams();
		wmlp.type = LayoutParams.TYPE_PHONE;
		// 设置图片格式,效果为背景透明
		wmlp.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦
		wmlp.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
		wmlp.gravity = Gravity.LEFT | Gravity.TOP;
		wmlp.x = 0;
		wmlp.y = 0;
		wmlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		layout = getLayout();
		wm.addView(layout, wmlp);
		layout.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		ImageView iv = (ImageView) layout.findViewById(1);
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("onClick", "onClick");
			}
		});
		iv.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// getRawX是触摸位置相对于屏幕的坐标,getX是相对于按钮的坐标
				wmlp.x = (int) event.getRawX() - layout.getMeasuredWidth() / 2;
				// 减25为状态栏的高度
				wmlp.y = (int) event.getRawY() - layout.getMeasuredHeight() / 2
						- 25;
				wm.updateViewLayout(layout, wmlp);
				return false;
			}
		});
	}

	private LinearLayout getLayout() {
		LinearLayout layout = new LinearLayout(this);
		ImageView iv = new ImageView(this);
		iv.setBackgroundResource((R.drawable.ic_launcher));
		iv.setId(1);
		layout.addView(iv);
		return layout;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (layout != null) {
			// 移除悬浮窗口
			wm.removeView(layout);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值