国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 互联网 > Android悬浮窗口

Android悬浮窗口

来源:程序员人生   发布时间:2014-09-11 23:35:47 阅读次数:2921次

FloatService:

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); } } }


权限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />


 

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生