开源项目之 AdFree Detector(屏蔽广告)

越嘉茂
2023-12-01

AdFree Detector 通过改变广告网络的IP地址、本地IP(改变hosts文件),使大部分的广告被屏蔽。

关键类Detector,如下:

public class Detector {

	/*
	 * com.bigtincan.android.adfree/.FreeMe
	 */
	private static final String ADFREE_PACKAGE_NAME = "com.bigtincan.android.adfree";
	private static final String ADFREE_MAIN_ACTIVITY = "com.bigtincan.android.adfree.FreeMe";

	public static boolean isAdFreeInstalled(Context context) { //是否初始化
		PackageManager pm = context.getPackageManager();
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.setClassName(ADFREE_PACKAGE_NAME, ADFREE_MAIN_ACTIVITY);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> apps = pm.queryIntentActivities(mainIntent, 0);
		if (apps.size() == 1) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isHostAltered(Context context, String hostname) { //是否主机已改变
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo().isConnected()) {
			try {
				/*
				 * 127.0.0.1 analytics.admob.com 127.0.0.1 analytics.live.com
				 * 127.0.0.1 analytics.msn.com 127.0.0.1 c.googleanalitics.net
				 * 127.0.0.1 feedads.googleadservices.com 127.0.0.1
				 * googleads.g.doubleclick.net 127.0.0.1
				 * googleads2.g.doubleclick.net
				 */
				InetAddress addr = null;
				if (hostname != null && hostname.length() > 0) {
					addr = InetAddress.getByName(hostname);
				} else {
					addr = InetAddress.getByName("googleads.g.doubleclick.net");
				}
				if (addr.getHostAddress().equals("127.0.0.1")) {
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		} else { // no network connection, we dont care
			return false;
		}
	}
}

项目使用它,需要添加的权限:

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

先检测它是否初始化了

boolean flag = Detector.isAdFreeInstalled(context);

确定特定主机是否改变

isAltered = Detector.isHostAltered(context, "analytics.admob.com");


项目下载

 类似资料: