Android 如何接入穿山甲广告?_怎么给手机养穿山甲广告数据,小码农也有大梦想

212 阅读5分钟

注意:平台SDK包中whiteList.txt 白名单上的资源不支持混淆

配置完成之后创建一个SDK初始化脚本内容如下 初始化调用是在开屏界面调用 调用初始化成功之后会自动调用开屏代码

package com.unity3d.player.chuanshanjia;
 
import android.content.Context;
import android.util.Log;
 
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdSdk;
 
 
/**
 * 可以用一个单例来保存TTAdManager实例,在需要初始化sdk的时候调用
 */
public class TTAdManagerHolder {
 
    private static final String TAG = "TTAdManagerHolder";
 
    private static boolean sInit;
 
    private static String appid;
    private static String appName;
    private static  TTAdManagerHolder _Instance;
 
    public static TTAdManager get() {
        return TTAdSdk.getAdManager();
    }
 
    public static TTAdManagerHolder Inst(){
        if (_Instance == null){
            _Instance = new TTAdManagerHolder();
        }
        return _Instance;
    }
 
    public void init(final Context context,String aid,String aname) {
        appid = aid;
        appName = aname;
        Log.d(TAG, "TTAdManagerHolderinit aid:"+aid+" aname:"+aname);
        doInit(context);
    }
 
    //step1:接入网盟广告sdk的初始化操作,详情见接入文档和穿山甲平台说明
    private void doInit(Context context) {
        if (!sInit) {
            TTAdSdk.init(context, buildConfig(context), new TTAdSdk.InitCallback() {
                @Override
                public void success() {
                    Log.i(TAG, "success: " );
                    CsjSplashActivity.Inst().loadSplashAd();
                }
                @Override
                public void fail(int code, String msg) {
                    Log.i(TAG, "fail:  code = " + code + " msg = " + msg);
                }
            });
            sInit = true;
        }
    }
 
 
    private TTAdConfig buildConfig(Context context) {
        //强烈建议在应用对应的Application#onCreate()方法中调用,避免出现content为null的异常
        return new TTAdConfig.Builder()
        .appId(appid)
        .useTextureView(true) //默认使用SurfaceView播放视频广告,当有SurfaceView冲突的场景,可以使用TextureView
        .appName(appName)
        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)//落地页主题
        .allowShowNotify(true) //是否允许sdk展示通知栏提示,若设置为false则会导致通知栏不显示下载进度
        .debug(true) //测试阶段打开,可以通过日志排查问题,上线时去除该调用
        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合,没有设置的网络下点击下载apk会有二次确认弹窗,弹窗中会披露应用信息
        .supportMultiProcess(false) //是否支持多进程,true支持
        .asyncInit(true) //是否异步初始化sdk,设置为true可以减少SDK初始化耗时。3450版本开始废弃~~
                //.httpStack(new MyOkStack3())//自定义网络库,demo中给出了okhttp3版本的样例,其余请自行开发或者咨询工作人员。
                .build();
    }
}

SDK集成完成之后开始接入SDK

工具类

ChuanShanJiaUtil

package com.unity3d.player.tools;
 
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.DisplayCutout;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class ChuanShanJiaUtil {
    public static float getScreenWidthDp(Context context){
        final float scale = context.getResources().getDisplayMetrics().density;
        float width = context.getResources().getDisplayMetrics().widthPixels;
        return width / (scale <= 0 ? 1 : scale) + 0.5f;
    }
 
    //全面屏、刘海屏适配
    public static float getHeight(Activity activity) {
        hideBottomUIMenu(activity);
        float height;
        int realHeight = getRealHeight(activity);
        if (ChuanShanJiaUtil.hasNotchScreen(activity)) {
            height = px2dip(activity, realHeight - getStatusBarHeight(activity));
        }else {
            height = px2dip(activity, realHeight);
        }
        return height;
    }
 
    public static void hideBottomUIMenu(Activity activity) {
        if (activity == null) {
            return;
        }
        try {
            //隐藏虚拟按键,并且全屏
            if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
                View v = activity.getWindow().getDecorView();
                v.setSystemUiVisibility(View.GONE);
            } else if (Build.VERSION.SDK_INT >= 19) {
                //for new api versions.
                View decorView = activity.getWindow().getDecorView();
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        //                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE;
                decorView.setSystemUiVisibility(uiOptions);
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    //获取屏幕真实高度,不包含下方虚拟导航栏
    public static int getRealHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealMetrics(dm);
        } else {
            display.getMetrics(dm);
        }
        int realHeight = dm.heightPixels;
        return realHeight;
    }
 
    //获取状态栏高度
    public static float getStatusBarHeight(Context context) {
        float height = 0;
        int resourceId = context.getApplicationContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getApplicationContext().getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }
 
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / (scale <= 0 ? 1 : scale) + 0.5f);
    }
 
    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
 
    /**
     * 判断是否是刘海屏
     * @return
     */
    public static boolean hasNotchScreen(Activity activity){
        return isAndroidPHasNotch(activity)
                || getInt("ro.miui.notch", activity) == 1
                || hasNotchAtHuawei(activity)
                || hasNotchAtOPPO(activity)
                || hasNotchAtVivo(activity);
    }
 
    /**
     * Android P 刘海屏判断
     * @param activity
     * @return
     */
    public static boolean isAndroidPHasNotch(Activity activity){
        boolean result = false;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            DisplayCutout displayCutout = null;
            try {
                WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets != null) {
                    displayCutout = windowInsets.getDisplayCutout();
                }
                if (displayCutout != null) {
                    result = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * 小米刘海屏判断.
     * @return 0 if it is not notch ; return 1 means notch
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static int getInt(String key,Activity activity) {
        int result = 0;
        if (isMiui()){
            try {
                ClassLoader classLoader = activity.getClassLoader();
                @SuppressWarnings("rawtypes")
                Class SystemProperties = classLoader.loadClass("android.os.SystemProperties");
                //参数类型
                @SuppressWarnings("rawtypes")
                Class[] paramTypes = new Class[2];
                paramTypes[0] = String.class;
                paramTypes[1] = int.class;
                Method getInt = SystemProperties.getMethod("getInt", paramTypes);
                //参数
                Object[] params = new Object[2];
                params[0] = new String(key);
                params[1] = new Integer(0);
                result = (Integer) getInt.invoke(SystemProperties, params);
 
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * 华为刘海屏判断
     * @return
     */
    public static boolean hasNotchAtHuawei(Context context) {
        boolean ret = false;
        try {
            ClassLoader classLoader = context.getClassLoader();
            Class HwNotchSizeUtil = classLoader.loadClass("com.huawei.android.util.HwNotchSizeUtil");
            Method get = HwNotchSizeUtil.getMethod("hasNotchInScreen");
            ret = (boolean) get.invoke(HwNotchSizeUtil);
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException e) {
        } catch (Exception e) {
        } finally {
            return ret;
        }
    }
 
    public static final int VIVO_NOTCH = 0x00000020;//是否有刘海
    public static final int VIVO_FILLET = 0x00000008;//是否有圆角
 
    /**
     * VIVO刘海屏判断
     * @return
     */
    public static boolean hasNotchAtVivo(Context context) {
        boolean ret = false;
        try {
            ClassLoader classLoader = context.getClassLoader();
            Class FtFeature = classLoader.loadClass("android.util.FtFeature");
            Method method = FtFeature.getMethod("isFeatureSupport", int.class);
            ret = (boolean) method.invoke(FtFeature, VIVO_NOTCH);
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException e) {
        } catch (Exception e) {
        } finally {
            return ret;
        }
    }
    /**
     * O-P-P-O刘海屏判断
     * @return
     */
    public static boolean hasNotchAtOPPO(Context context) {
        String temp = "com.kllk.feature.screen.heteromorphism";
        String name = getKllkDecryptString(temp);
        return context.getPackageManager().hasSystemFeature(name);
    }
 
    public static boolean isMiui() {
        boolean sIsMiui = false;
        try {
            Class<?> clz = Class.forName("miui.os.Build");
            if (clz != null) {
                sIsMiui = true;
                //noinspection ConstantConditions
                return sIsMiui;
            }
        } catch (Exception e) {
            // ignore
        }
        return sIsMiui;
    }
 
    /**
     *用于o-p-p-o 版本隐私协议
     */
    public static String getKllkDecryptString(String encryptionString) {
 
        if (TextUtils.isEmpty(encryptionString)) {
            return "";
        }
        String decryptTag = "";
        String decryptCapitalized = "O" + "P" + "P" + "O";
        String decrypt = "o" + "p" + "p" + "o";
        if (encryptionString.contains("KLLK")) {
            decryptTag =  encryptionString.replace("KLLK", decryptCapitalized);
        } else if (encryptionString.contains("kllk")) {
            decryptTag = encryptionString.replace("kllk", decrypt);
        }
        return decryptTag;
 
    }
 
    public static void setViewSize(View view, int width, int height) {
        if (view.getParent() instanceof FrameLayout) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();
            lp.width = width;
            lp.height = height;
            view.setLayoutParams(lp);
            view.requestLayout();
        } else if (view.getParent() instanceof RelativeLayout) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
            lp.width = width;
            lp.height = height;
            view.setLayoutParams(lp);
            view.requestLayout();
        } else if (view.getParent() instanceof LinearLayout) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) view.getLayoutParams();
            lp.width = width;
            lp.height = height;
            view.setLayoutParams(lp);
            view.requestLayout();
        }
    }
 
    public static int getScreenWidthInPx(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }
 
    public static int getScreenHeightInPx(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }
 
    public static int getScreenHeight(Context context) {
        return (int) (getScreenHeightInPx(context) + getStatusBarHeight(context));
    }
 
    public static void removeFromParent(View view) {
        if (view != null) {
            ViewParent vp = view.getParent();
            if (vp instanceof ViewGroup) {
                ((ViewGroup) vp).removeView(view);
            }
        }
    }
 
    /**
     * 获取全面屏宽高
     * @param context
     * @return
     */
    public static int[] getScreenSize(Context context) {
        int[] size = new int[]{0,0};
        if (context == null){
            return size;
        }
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealMetrics(dm);
        } else {
            display.getMetrics(dm);
        }
        size[0] = dm.widthPixels;
        size[1] = dm.heightPixels;
        return size;
    }
}

ShowSeqUtils

package com.unity3d.player.tools;
 
import android.os.Environment;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ShowSeqUtils {
    private FileReader fr;
    private BufferedReader br;
    private FileWriter fw;
    private BufferedWriter bw;
 
 
    public int loadShowSeq(){
        int show_seq = 1;
        //获取当前日期字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String data = sdf.format(new Date());
        //读取本地缓存show_seq的文件
        try {
            String rootPath =  Environment.getExternalStorageDirectory().getPath();
            File file = new File(rootPath + "/Android/data/com.snssdk.api/cache/adloadSeqTemp.txt");
            if (!file.exists()) {
                file.createNewFile();
                return show_seq;
            }
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            String line = "";
            while ((line = br.readLine()) != null) {
                String[] temp = line.split(",");
                if (temp[0].equals(data)){
                    //日期相同返回字段
                    show_seq = Integer.parseInt(temp[1]);
                }
            }
            return show_seq;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fr!=null){
                    fr.close();
                }
                if(br!=null){
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return show_seq;
    }
 
    public void writeToFile(int show_seq){
        //获取当前日期字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String data = sdf.format(new Date());
        String content = data+","+show_seq;
        //读取本地缓存show_seq的文件
        try {
            String rootPath =  Environment.getExternalStorageDirectory().getPath();
            File file = new File(rootPath + "/Android/data/com.snssdk.api/cache/");
            if (!file.exists()) {
                file.mkdir();
            }
            String filename = file.getAbsolutePath()+"/adloadSeqTemp.txt";
            file = new File(filename);
            if(!file.exists()){
                file.createNewFile();
            }
            fw = new FileWriter(file, false);
            fw.write(content);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw!=null){
                    fw.flush();
                    fw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

TToast

package com.unity3d.player.tools;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
 
public final class TToast {
    private static Toast sToast;
 
    public static void show(Context context, String msg) {
        show(context, msg, Toast.LENGTH_SHORT);
    }
 
    public static void show(Context context, String msg, int duration) {
        Toast toast = getToast(context);
        if (toast != null) {
            toast.setDuration(duration);
            toast.setText(String.valueOf(msg));
            toast.show();
        } else {
            Log.i("TToast", "toast msg: " + String.valueOf(msg));
        }
    }
 
    @SuppressLint("ShowToast")
    private static Toast getToast(Context context) {
        if (context == null) {
### 最后

我见过很多技术leader在面试的时候,遇到处于迷茫期的大龄程序员,比面试官年龄都大。这些人有一些共同特征:可能工作了78年,还是每天重复给业务部门写代码,工作内容的重复性比较高,没有什么技术含量的工作。问到这些人的职业规划时,他们也没有太多想法。

其实30岁到40岁是一个人职业发展的黄金阶段,一定要在业务范围内的扩张,技术广度和深度提升上有自己的计划,才有助于在职业发展上有持续的发展路径,而不至于停滞不前。

不断奔跑,你就知道学习的意义所在!

**以上进阶BATJ大厂学习资料可以免费分享给大家,需要完整版的朋友,【[点这里可以看到全部内容](https://github.com/a120464/Android-P7/blob/master/Android%E5%BC%80%E5%8F%91%E4%B8%8D%E4%BC%9A%E8%BF%99%E4%BA%9B%EF%BC%9F%E5%A6%82%E4%BD%95%E9%9D%A2%E8%AF%95%E6%8B%BF%E9%AB%98%E8%96%AA%EF%BC%81.md)】。**