悬浮窗口和利用服务实现流氓广告弹窗

刚来公司就被告知做一个推广模块,一开始没明白过来,因为以前从来没有做过,一头雾水,不知道从哪里下手,经过研究发现,其实就是利用广告实现WindowManager弹出的窗口。

思路是这样的:先用windowmanager创建一个悬浮窗,然后再服务中开启悬浮窗,为了流氓一点,不要绑定服务,直接开启,然后监听是不是桌面,不是桌面就让弹出悬浮窗,更流氓一点就是,在服务中设置定时器,每隔几秒钟去检查一遍,看是不是桌面,不是就显示悬浮窗。怎么样流氓吧!


下面就上代码:

窗口代码:

package com.ys.update.view;

import java.lang.reflect.Field;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ys.update.R;
import com.ys.update.activity.NotificationUpdateActivity;
import com.ys.update.dialog.MyWindowManager;
import com.ys.update.service.FloatWindowService;
import com.ys.update.utils.SharedPreferencesUtil;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FloatWindowSmallView extends LinearLayout {

	/**
	 * 记录小悬浮窗的宽度
	 */
	public static int viewWidth;

	/**
	 * 记录小悬浮窗的高度
	 */
	public static int viewHeight;

	/**
	 * 记录系统状态栏的高度
	 */
	 private static int statusBarHeight;

	@SuppressWarnings("unused")
	private WindowManager windowManager;

	@SuppressWarnings("unused")
	private WindowManager.LayoutParams mParams;

	/**
	 * 记录当前手指位置在屏幕上的横坐标值
	 */
	private float xInScreen;

	/**
	 * 记录当前手指位置在屏幕上的纵坐标值
	 */
	private float yInScreen;

	/**
	 * 记录手指按下时在屏幕上的横坐标的值
	 */
	private float xDownInScreen;

	/**
	 * 记录手指按下时在屏幕上的纵坐标的值
	 */
	private float yDownInScreen;

	@SuppressWarnings("unused")
	private float xInView;

	@SuppressWarnings("unused")
	private float yInView;
	
	@SuppressWarnings("unused")
	private Context context;

	private View inflate;

	public FloatWindowSmallView(final Context context) {
		super(context);
		this.context = context;
		windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		inflate = LayoutInflater.from(context).inflate(R.layout.desklayout, this);
//		inflate.findViewById(R.id.RelativeLayout_ll).getBackground().setAlpha(10);
		View view = inflate.findViewById(R.id.small_window_layout);
		viewWidth = view.getLayoutParams().width;
		viewHeight = view.getLayoutParams().height;
		TextView name = (TextView) inflate.findViewById(R.id.desklayout_title);
		TextView content = (TextView) inflate.findViewById(R.id.desklayout_content);
		ImageView imageView = (ImageView) inflate.findViewById(R.id.desklayout_image);
		
		ImageLoader.getInstance().displayImage(SharedPreferencesUtil.getStringData(context, "bannerImg", ""), imageView, ImageLoad.getOptions(), ImageLoad.getImageLoadingListener());
		name.setText(SharedPreferencesUtil.getStringData(context, "title", ""));
		content.setText(SharedPreferencesUtil.getStringData(context, "content", ""));
		
		inflate.findViewById(R.id.desklayout_error).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				closeDesk();
			}
		});
		
		inflate.findViewById(R.id.downloader).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent in = new Intent();
				in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				in.setClass(context, NotificationUpdateActivity.class);
				context.startActivity(in);
				Intent intent = new Intent(getContext(), FloatWindowService.class);
				context.stopService(intent);
				closeDesk();
			}
		});
	}
	
	/**
	 * 关闭悬浮窗。
	 */
	private void closeDesk() {
		MyWindowManager.removeSmallWindow(getContext());
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			closeDesk();
			// 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
			xInView = event.getX();
			yInView = event.getY();
			xDownInScreen = event.getRawX();
			yDownInScreen = event.getRawY() - getStatusBarHeight();
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			break;
		case MotionEvent.ACTION_MOVE:
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			break;
		case MotionEvent.ACTION_UP:
			// 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
			if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
				openBigWindow();
			}
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
	 * 
	 * @param params
	 *            小悬浮窗的参数
	 */
	public void setParams(WindowManager.LayoutParams params) {
		mParams = params;
	}
	
	/**
	 * 打开大悬浮窗,同时关闭小悬浮窗。
	 */
	private void openBigWindow() {
//		Intent in = new Intent();
//		in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		in.setClass(context, NotificationUpdateActivity.class);
//		context.startActivity(in);
		MyWindowManager.removeSmallWindow(getContext());
	}

	/**
	 * 用于获取状态栏的高度。
	 * 
	 * @return 返回状态栏高度的像素值。
	 */
	private int getStatusBarHeight() {
		if (statusBarHeight == 0) {
			try {
				Class<?> c = Class.forName("com.android.internal.R$dimen");
				Object o = c.newInstance();
				Field field = c.getField("status_bar_height");
				int x = (Integer) field.get(o);
				statusBarHeight = getResources().getDimensionPixelSize(x);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusBarHeight;
	}

}

控制窗口的创建和移除:

package com.ys.update.dialog;

import com.ys.update.utils.JsonUtils;
import com.ys.update.view.FloatWindowBigView;
import com.ys.update.view.FloatWindowSmallView;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class MyWindowManager {

	/**
	 * 小悬浮窗View的实例
	 */
	private static FloatWindowSmallView smallWindow;

	/**
	 * 大悬浮窗View的实例
	 */
	private static FloatWindowBigView bigWindow;

	/**
	 * 小悬浮窗View的参数
	 */
	private static LayoutParams smallWindowParams;

	/**
	 * 大悬浮窗View的参数
	 */
	private static LayoutParams bigWindowParams;

	/**
	 * 用于控制在屏幕上添加或移除悬浮窗
	 */
	private static WindowManager mWindowManager;

	/**
	 * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 */
	@SuppressWarnings("deprecation")
	public static void createSmallWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (smallWindow == null) {
			smallWindow = new FloatWindowSmallView(context);
			if (smallWindowParams == null) {
				smallWindowParams = new LayoutParams();
				smallWindowParams.type = LayoutParams.TYPE_PHONE;
				smallWindowParams.format = PixelFormat.RGBA_8888;
				smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
						| LayoutParams.FLAG_NOT_FOCUSABLE;
				smallWindowParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
				smallWindowParams.width = FloatWindowSmallView.viewWidth;
				smallWindowParams.height = FloatWindowSmallView.viewHeight;
				smallWindowParams.x = screenWidth;
				smallWindowParams.y = screenHeight / 5;
			}
			smallWindow.setParams(smallWindowParams);
			windowManager.addView(smallWindow, smallWindowParams);
		}
	}

	/**
	 * 将小悬浮窗从屏幕上移除。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void removeSmallWindow(Context context) {
		if (smallWindow != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(smallWindow);
			smallWindow = null;
		}
	}

	/**
	 * 创建一个大悬浮窗。位置为屏幕正中间。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 */
	@SuppressWarnings("deprecation")
	public static void createBigWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (bigWindow == null) {
			bigWindow = new FloatWindowBigView(context);
			if (bigWindowParams == null) {
				bigWindowParams = new LayoutParams();
				bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2;
				bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2;
				bigWindowParams.type = LayoutParams.TYPE_PHONE;
				bigWindowParams.format = PixelFormat.RGBA_8888;
				bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
				bigWindowParams.width = FloatWindowBigView.viewWidth;
				bigWindowParams.height = FloatWindowBigView.viewHeight;
			}
			windowManager.addView(bigWindow, bigWindowParams);
		}
	}

	/**
	 * 将大悬浮窗从屏幕上移除。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void removeBigWindow(Context context) {
		if (bigWindow != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(bigWindow);
			bigWindow = null;
		}
	}

	/**
	 * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
	 * 
	 * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
	 */
	public static boolean isWindowShowing() {
		return smallWindow != null || bigWindow != null;
	}

	/**
	 * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
	 */
	private static WindowManager getWindowManager(Context context) {
		if (mWindowManager == null) {
			mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		}
		return mWindowManager;
	}
}

定时检查窗口是否存在的服务:

package com.ys.update.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.ys.update.dialog.MyWindowManager;
import com.ys.update.utils.JsonUtils;
import com.ys.update.utils.LogUtil;
import com.ys.update.utils.PackageUtils;
import com.ys.update.utils.SharedPreferencesUtil;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

public class FloatWindowService extends Service {

	private Handler handler = new Handler();

	private Timer timer;

	private String count;

	private String appId;

	private String typeId;
	
	private Context context;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		context = this;
		typeId = intent.getStringExtra("typeId");
		appId = intent.getStringExtra("appId");
		count = intent.getStringExtra("count");
		if (timer == null) {
			timer = new Timer();
			timer.scheduleAtFixedRate(new RefreshTask(), 0, 3000); // 每隔3秒去重新检查一遍
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		timer.cancel();
		timer = null;
	}

	class RefreshTask extends TimerTask {

		@Override
		public void run() {
			if (!isHome() && !MyWindowManager.isWindowShowing()) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						JsonUtils.downApply(getApplicationContext(), typeId, appId, count);
						LogUtil.i("FloatWindowService", "typeId = " + typeId);
						int coun = 0;
						ArrayList<String> appNames = PackageUtils.getAppName(getApplicationContext());
						if (appNames.contains(SharedPreferencesUtil.getStringData(getApplicationContext(), "name", "")) == false && !TextUtils.isEmpty(SharedPreferencesUtil.getStringData(getApplicationContext(), "popTimes", ""))) {
							LogUtil.i("BannerWindow", SharedPreferencesUtil.getStringData(getApplicationContext(), "popTimes", ""));
							if (coun <= Integer.valueOf(SharedPreferencesUtil.getStringData(getApplicationContext(), "popTimes", ""))) {
								switch (Integer.valueOf(typeId)) {
								case 1:
									LogUtil.i("FloatWindowService", "typeId------ = " + typeId);
//									CustomWindow.createDownDialog(context, typeId, appId, count);
									MyWindowManager.createBigWindow(context);
									break;

								case 2:
									LogUtil.i("FloatWindowService", "typeId++++++++++++ = " + typeId);
									MyWindowManager.createSmallWindow(context);
									break;
								}
								
								coun++;
							}
						}
					}
				});
			}
			else if (isHome() && MyWindowManager.isWindowShowing()) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						MyWindowManager.removeSmallWindow(getApplicationContext());
						MyWindowManager.removeBigWindow(getApplicationContext());
					}
				});
			}
//			else if (!isHome() && MyWindowManager.isWindowShowing()) {
//				handler.post(new Runnable() {
//					@Override
//					public void run() {
						MyWindowManager.updateUsedPercent(getApplicationContext());
//					}
//				});
//			}
		}

	}

	private boolean isHome() {
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		return getHomes().contains(rti.get(0).topActivity.getPackageName());
	}

	private List<String> getHomes() {
		List<String> names = new ArrayList<String>();
		PackageManager packageManager = this.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo ri : resolveInfo) {
			names.add(ri.activityInfo.packageName);
		}
		return names;
	}
}

清单文件的配置:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ys.update"
    android:versionCode="1"
    android:sharedUserId="main.mainplugin"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="6" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" >
    </uses-permission>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.GET_TASKS" />

    <application
        android:name="com.ys.update.app.MyApp"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme"
        android:label="@string/app_name" >
        <activity
            android:name="com.ys.update.activity.NotificationUpdateActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.ys.update.service.DownloadService" />
        <service android:name="com.ys.update.service.FloatWindowService" />
        
    </application>

</manifest>

好了,到这里就完成了。

下载demo,点击这里

测试代码点击这里




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值