广播机制1111111111

最后效果
在这里插入图片描述

在这里插入图片描述
前台代码:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:id="@+id/smsStatusTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="等待发送广播..."
        android:textSize="20sp"
        android:layout_marginBottom="20dp"/>
    <Button
        android:id="@+id/sendBroadcastButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送广播"/>

</LinearLayout>



后台
MainActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String CUSTOM_SMS_RECEIVED_ACTION =
            "com.example.myapplication.ACTION_NEW_SMS_RECEIVED";
    private MyCustomReceiver customReceiver; // 自定义Receiver
    private IntentFilter intentFilter;
    private TextView smsStatusTextView;
    private Button sendBroadcastButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 布局文件

        smsStatusTextView = findViewById(R.id.smsStatusTextView); // TextView控件ID
        sendBroadcastButton = findViewById(R.id.sendBroadcastButton); // 按钮ID

// --- 动态注册广播 ---
        customReceiver = new MyCustomReceiver();

// 设置UI更新回调(通过Receiver的接口)
        customReceiver.setOnUIUpdateListener(message ->
                smsStatusTextView.setText(message)
        );

        intentFilter = new IntentFilter();
        intentFilter.addAction(CUSTOM_SMS_RECEIVED_ACTION); // 添加监听Action

        registerReceiver(customReceiver, intentFilter); // 注册广播
// --- 注册结束 ---

// --- 按钮点击发送广播 ---
        sendBroadcastButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent customBroadcastIntent = new Intent(
                        CUSTOM_SMS_RECEIVED_ACTION
                );
                sendBroadcast(customBroadcastIntent); // 发送普通广播
            }
        });
// --- 监听器结束 ---
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(customReceiver); // 注销广播
        customReceiver = null;
    }
}

创建类
MyCustomReceiver.java

package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;

public class MyCustomReceiver extends BroadcastReceiver {
    private static final String TAG = "MyCustomReceiver";
    private OnUIUpdateListener uiUpdateListener;

    // 定义UI更新回调接口
    public interface OnUIUpdateListener {
        void updateStatus(String message);
    }

    // 设置回调的方法
    public void setOnUIUpdateListener(OnUIUpdateListener listener) {
        this.uiUpdateListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Received broadcast: " + intent.getAction());

        String CUSTOM_ACTION = "com.example.myapplication.ACTION_NEW_SMS_RECEIVED";

        // 正确获取Action并匹配
        if (CUSTOM_ACTION.equals(intent.getAction())) {
            // 通过回调更新UI(而非直接操作TextView)
            if (uiUpdateListener != null) {
                uiUpdateListener.updateStatus("收到新的短信息了。 (通过自定义广播)");
                Log.d(TAG, "UI update callback triggered.");
            } else {
                Log.e(TAG, "UI update listener is null.");
            }
        }
    }
}

使用自定义广播机制完成广播接收者的定义,实例化,注册。点击“发送广播”按钮后,发送一条自定义广播,模拟接收到短信的广播,然后接收者在收到广播后,在主界面显示“收到新的短信息了…”。

以上需求在下面代码中实现/* * Copyright (C) 2020 Rock-Chips Corporation, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.connectivity; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.ContentResolver; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.PowerManager; import android.os.SystemProperties; import android.provider.Settings; import android.util.Log; public class WifiSleepController { private static final String LOG_TAG = "WifiSleepController"; private static final boolean DBG = true; private static final String ACTION_WIFI_SLEEP_TIMEOUT_ALARM = "WifiSleepController.TimeoutForWifiSleep"; private static final String PERSISTENT_PROPERTY_WIFI_SLEEP_DELAY = "persist.wifi.sleep.delay.ms"; private static final String PERSISTENT_PROPERTY_WIFI_SLEEP_FLAG = "persist.wifi.sleep.flag"; private static final int DEFAULT_WIFI_SLEEP_DELAY_MS = 15 * 60 * 1000; private static final String PERSISTENT_PROPERTY_BT_SLEEP_FLAG = "persist.bt.sleep.flag"; static final int WIFI_DISABLED = 0; static final int WIFI_ENABLED = 1; static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2; static final int BT_DISABLED = 0; static final int BT_ENABLED = 1; static final int BT_ENABLED_AIRPLANE_OVERRIDE = 2; private Context mContext; private AlarmManager mAlarmManager; private WifiManager mWifiManager; private PowerManager.WakeLock mWifiWakeLock; private WifiReceiver mWifiReceiver = new WifiReceiver(); private PendingIntent mWifiSleepIntent = null; private boolean mCharging = false; private boolean mIsScreenON = true; private boolean mBtPowerDownSetting = SystemProperties.getBoolean("persist.bt.power.down", false); private boolean mBtIsOpened = false; private boolean mWifiIsOpened = false; public WifiSleepController(Context context) { mContext = context; PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); mWifiWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiSleepPowerDown"); mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_BOOT_COMPLETED); filter.addAction(Intent.ACTION_BATTERY_CHANGED); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(ACTION_WIFI_SLEEP_TIMEOUT_ALARM); mContext.registerReceiver(mWifiReceiver, filter); } private class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); log("onReceive, action=" + action); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { updateChargingState(intent); } else if (action.equals(Intent.ACTION_SCREEN_ON)) { log("HHDEVSetProperty 1111111111"); boolean wakeFromUltra = SystemProperties.getBoolean("wifi.ultra.enabled", false); SystemProperties.set("wifi.ultra.enabled", "false"); if(wakeFromUltra){ setWifiEnabled(true); log("HHDEVSetProperty 4444"); setWifiEnabled(false); } // log("HHDEVSetProperty 22222"); // boolean wakeFromDeep = SystemProperties.getBoolean("wifi.deep.enabled", true); // log("HHDEVSetProperty wakeFromDeep = "+wakeFromDeep); // SystemProperties.set("wifi.deep.enabled", "true"); // if(wakeFromDeep){ // setWifiEnabled(false); // log("HHDEVSetProperty 如果开着wifi休眠进入ultra唤醒后能开吗"); // setWifiEnabled(true); // } mIsScreenON = true; exitSleepState(); SystemProperties.set(PERSISTENT_PROPERTY_WIFI_SLEEP_FLAG, "false"); SystemProperties.set(PERSISTENT_PROPERTY_BT_SLEEP_FLAG, "false"); } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { // setWifiEnabled(false); mIsScreenON = false; log("isScanAlwaysAvailable = " + mWifiManager.isScanAlwaysAvailable()); boolean mWifiSleepConfig = SystemProperties.getBoolean("ro.wifi.sleep.power.down", false); if(mWifiSleepConfig && mWifiManager.isScanAlwaysAvailable()) { mWifiManager.setScanAlwaysAvailable(false); } mBtIsOpened = getBtIsEnabled(); mWifiIsOpened = getWifiIsEnabled(); if (shouldStartWifiSleep()) { setWifiSleepAlarm(); }else if(shouldStartBtSleep()){//check if only bt setWifiSleepAlarm(); } } else if (action.contains(ACTION_WIFI_SLEEP_TIMEOUT_ALARM)) { //Sometimes we receive this action after SCREEN_ON. //Turn off wifi should only happen when SCREEN_OFF. if(!mIsScreenON) { if(mWifiIsOpened) { setWifiEnabled(false); SystemProperties.set(PERSISTENT_PROPERTY_WIFI_SLEEP_FLAG, "true"); } if(mBtIsOpened && mBtPowerDownSetting){ setBtEnabled(false); SystemProperties.set(PERSISTENT_PROPERTY_BT_SLEEP_FLAG, "true");; } } } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { boolean mWifiSleepFlag = SystemProperties.getBoolean(PERSISTENT_PROPERTY_WIFI_SLEEP_FLAG, false); log("mWifiSleepFlag is " + mWifiSleepFlag); if(mWifiSleepFlag && !getWifiIsEnabled()) { setWifiEnabled(true); } boolean mBtSleepFlag = SystemProperties.getBoolean(PERSISTENT_PROPERTY_BT_SLEEP_FLAG, false); log("mBtSleepFlag is " + mBtSleepFlag); if(mBtSleepFlag && !getBtIsEnabled()) { setBtEnabled(true); } } } } private void updateChargingState(Intent batteryChangedIntent) { final int status = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN); boolean charging = status == BatteryManager.BATTERY_STATUS_FULL || status == BatteryManager.BATTERY_STATUS_CHARGING; log("updateChargingState, mCharging: " + charging); if (mCharging != charging) { log("updateChargingState, mCharging: " + charging); //no need update sleep state right now, because charge //state changed will cause SCREEN_ON mCharging = charging; } } private int wifiSleepPolicyMode() { return Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.WIFI_SLEEP_POLICY, Settings.Global.WIFI_SLEEP_POLICY_NEVER); } private boolean shouldStartWifiSleep() { log("shouldStartWifiSleep: isWifiOpen = " + mWifiIsOpened); if(mWifiIsOpened) { if(wifiSleepPolicyMode() == Settings.Global.WIFI_SLEEP_POLICY_DEFAULT) { return true; } else if(wifiSleepPolicyMode() == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) { if(!mCharging){ return true; } } } return false; } private boolean getWifiIsEnabled() { final ContentResolver cr = mContext.getContentResolver(); return Settings.Global.getInt(cr, Settings.Global.WIFI_ON, WIFI_DISABLED) == WIFI_ENABLED || Settings.Global.getInt(cr, Settings.Global.WIFI_ON, WIFI_DISABLED) == WIFI_ENABLED_AIRPLANE_OVERRIDE; } private void setWifiSleepAlarm() { long delayMs = SystemProperties.getInt(PERSISTENT_PROPERTY_WIFI_SLEEP_DELAY, DEFAULT_WIFI_SLEEP_DELAY_MS); Intent intent = new Intent(ACTION_WIFI_SLEEP_TIMEOUT_ALARM); mWifiSleepIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMs, mWifiSleepIntent); log("setWifiSleepAlarm: set alarm :" + delayMs + "ms"); } private void setWifiEnabled(boolean enable) { log("setWifiEnabled " + enable); if (!mWifiWakeLock.isHeld()) { log("---- mWifiWakeLock.acquire ----"); mWifiWakeLock.acquire(); } mWifiManager.setWifiEnabled(enable); if (mWifiWakeLock.isHeld()) { try { Thread.sleep(2000); } catch (InterruptedException ignore) { } log("---- mWifiWakeLock.release ----"); mWifiWakeLock.release(); } } private void exitSleepState() { log("exitSleepState()"); if (mWifiSleepIntent != null) { if(mWifiIsOpened && !getWifiIsEnabled()){ setWifiEnabled(true); } if(mBtIsOpened && !getBtIsEnabled()){ setBtEnabled(true); } removeWifiSleepAlarm(); } } private void removeWifiSleepAlarm() { log("removeWifiSleepAlarm..."); if (mWifiSleepIntent != null) { mAlarmManager.cancel(mWifiSleepIntent); mWifiSleepIntent = null; } } private boolean shouldStartBtSleep() { log("shouldStartBtSleep: isBtOpen = " + mBtIsOpened); if(mBtIsOpened && mBtPowerDownSetting) { if(wifiSleepPolicyMode() == Settings.Global.WIFI_SLEEP_POLICY_DEFAULT) { return true; } else if(wifiSleepPolicyMode() == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) { if(!mCharging){ return true; } } } return false; } private boolean getBtIsEnabled() { final ContentResolver cr = mContext.getContentResolver(); return Settings.Global.getInt(cr, Settings.Global.BLUETOOTH_ON, 0) == BT_ENABLED || Settings.Global.getInt(cr, Settings.Global.BLUETOOTH_ON, 0) == BT_ENABLED_AIRPLANE_OVERRIDE; } private void setBtEnabled(boolean enable){ log("setBtEnabled " + enable); BluetoothAdapter mAdapter= BluetoothAdapter.getDefaultAdapter(); if(enable) mAdapter.enable(); else mAdapter.disable(); } private static void log(String s) { Log.d(LOG_TAG, s); } }
09-28
package com.weishitechsub.kdcxqwb.fragment.remind; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.anythink.core.api.ATAdConst; import com.anythink.core.api.ATAdInfo; import com.anythink.core.api.ATNetworkConfirmInfo; import com.anythink.core.api.ATShowConfig; import com.anythink.core.api.AdError; import com.anythink.dlopt.api.ATAppDownloadListener; import com.anythink.interstitial.api.ATInterstitial; import com.anythink.interstitial.api.ATInterstitialAutoAd; import com.anythink.interstitial.api.ATInterstitialAutoEventListener; import com.anythink.interstitial.api.ATInterstitialAutoLoadListener; import com.anythink.interstitial.api.ATInterstitialExListener; import com.anythink.nativead.api.ATNative; import com.anythink.nativead.api.ATNativeAdView; import com.anythink.nativead.api.ATNativeDislikeListener; import com.anythink.nativead.api.ATNativeEventExListener; import com.anythink.nativead.api.ATNativeNetworkListener; import com.anythink.nativead.api.ATNativePrepareExInfo; import com.anythink.nativead.api.ATNativePrepareInfo; import com.anythink.nativead.api.ATNativeView; import com.anythink.nativead.api.NativeAd; import com.anythink.nativead.api.NativeAdInteractionType; import com.hfd.common.base.BaseFragment; import com.weishitechsub.kdcxqwb.LCAppcation; import com.weishitechsub.kdcxqwb.MainActivity; import com.weishitechsub.kdcxqwb.R; import com.weishitechsub.kdcxqwb.ad.AdConst; import com.weishitechsub.kdcxqwb.ad.base.BaseActivity; import com.weishitechsub.kdcxqwb.ad.util.SDKUtil; import com.weishitechsub.kdcxqwb.ad.util.SelfRenderViewUtil; import com.weishitechsub.kdcxqwb.bean.ListBean; import com.weishitechsub.kdcxqwb.fragment.Adapter.MyCourierAdapter; import com.weishitechsub.kdcxqwb.fragment.Adapter.RemindListAdapter; import com.weishitechsub.kdcxqwb.fragment.home.HomeFragment; import com.weishitechsub.kdcxqwb.fragment.home.MyCourierActivity; import com.weishitechsub.kdcxqwb.utils.JsonUtils; import com.weishitechsub.kdcxqwb.utils.ReminderManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RemindFragment extends BaseFragment { private static final String TAG = RemindFragment.class.getSimpleName(); private RecyclerView rv; private RemindListAdapter adapter; private List<ListBean> fullDataList; /** * 插屏广告 */ private ATInterstitial mInterstitialAd; /** 原生广告*/ private final List<String> mData = new ArrayList<>(); private ATNative mATNative; private NativeAd mNativeAd; private ATNativeView mWoDeATNativeView; private View mWoDeSelfRenderView; @Override protected int setLayout() { return R.layout.fragment_remind; } @Override protected void initView() { rv = fvbi(R.id.rv); rv.setLayoutManager(new LinearLayoutManager(getContext())); adapter = new RemindListAdapter(getContext()); adapter.setTrackList(parseCourierJson()); rv.setAdapter(adapter); /** 原生广告*/ mWoDeATNativeView = fvbi(R.id.native_ad_view); mWoDeSelfRenderView = fvbi(R.id.native_selfrender_view); /** 原生视频广告*/ if (LCAppcation.getInstance().isShowAd(44)) { //准备加载广告 initYsATNativeAd(LCAppcation.naviteAdId); final int adViewWidth = mWoDeATNativeView.getWidth() != 0 ? mWoDeATNativeView.getWidth() : getResources().getDisplayMetrics().widthPixels; final int adViewHeight = adViewWidth * 3 / 4; loadYsAd(adViewWidth, adViewHeight); isYsAdReady(); new Handler().postDelayed(() -> { ATNative.entryAdScenario(LCAppcation.naviteAdId, AdConst.SCENARIO_ID.NATIVE_AD_SCENARIO); if (isYsAdReady()) { showYsAd(); } }, 2000); } /** 插屏广告*/ if (LCAppcation.getInstance().isShowAd(2)) { initCpInterstitialAd(); initCpAutoLoad(); isCpAdReady(); new Handler().postDelayed(() -> { ATInterstitial.entryAdScenario(LCAppcation.interstitialAdId, AdConst.SCENARIO_ID.INTERSTITIAL_AD_SCENARIO); if (mInterstitialAd.isAdReady()) { showCpAd(); } }, 2000); // 延时2000毫秒(2秒)后跳转 } } @Override protected void initData() { refreshRemindedList(); // 直接刷新 } @Override public void onResume() { super.onResume(); /** 原生视频广告*/ if (mNativeAd != null) { mNativeAd.onResume(); } refreshRemindedList(); // 页面可见时重新加载 } // RemindFragment.java private void refreshRemindedList() { Context context = getContext(); if (context == null) return; // 直接从 ReminderManager 获取已提醒的条目 List<ListBean> remindedList = ReminderManager.getInstance(context).getRemindedItems(); adapter.setNewInstance(remindedList); if (remindedList.isEmpty()) { Toast.makeText(context, "暂无提醒中的快递", Toast.LENGTH_SHORT).show(); } else { Log.d("RemindFragment", "显示 " + remindedList.size() + " 个提醒项"); } } @Override public void onStart() { super.onStart(); ReminderManager.getInstance(getContext()).setOnReminderChangeListener(() -> { new Handler(Looper.getMainLooper()).post(this::refreshRemindedList); }); } @Override public void onStop() { super.onStop(); ReminderManager.getInstance(getContext()).removeListener(); } private List<ListBean> getDataFromSomewhere() { MyCourierActivity activity = (MyCourierActivity) getActivity(); if (activity != null) { List<ListBean> data = activity.getCurrentCourierList(); return data != null ? new ArrayList<>(data) : new ArrayList<>(); } return new ArrayList<>(); } @Override protected void initClick() {} private List<ListBean> parseCourierJson() { String jsonString = JsonUtils.loadJSONFromAsset(mContext.getAssets(), "delivery_list.json"); List<ListBean> couriers = new ArrayList<>(); try { JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject item = jsonArray.getJSONObject(i); String title = item.getString("title"); String des = item.getString("des"); String value = item.getString("value"); couriers.add(new ListBean(title,value,"","","")); } } catch (JSONException e) { e.printStackTrace(); } return couriers; } private void exitYsNativePanel() { mData.clear(); destroyYsAd(); } public void destroyYsAd() { if (mNativeAd != null) { mWoDeATNativeView.removeAllViews(); mWoDeATNativeView.setVisibility(View.GONE); mNativeAd.destory(); } } @Override public void onPause() { /** 原生视频广告*/ if (mNativeAd != null) { mNativeAd.onPause(); } super.onPause(); } @Override public void onDestroy() { super.onDestroy(); /** * 插屏广告 */ for (Map.Entry<String, Boolean> entry : mCpAutoLoadPlacementIdMap.entrySet()) { ATInterstitialAutoAd.removePlacementId(entry.getKey()); } if (mInterstitialAd != null) { mInterstitialAd.setAdSourceStatusListener(null); mInterstitialAd.setAdDownloadListener(null); mInterstitialAd.setAdListener(null); mInterstitialAd.setAdMultipleLoadedListener(null); } /** 原生视频广告*/ destroyYsAd(); if (mATNative != null) { mATNative.setAdListener(null); mATNative.setAdSourceStatusListener(null); mATNative.setAdMultipleLoadedListener(null); } } /** * 插屏广告 */ private final Map<String, Boolean> mCpAutoLoadPlacementIdMap = new HashMap<>(); private final ATInterstitialAutoLoadListener autoCpLoadListener = new ATInterstitialAutoLoadListener() { @Override public void onInterstitialAutoLoaded(String placementId) { Log.i(TAG, "PlacementId:" + placementId + ": onInterstitialAutoLoaded"); } @Override public void onInterstitialAutoLoadFail(String placementId, AdError adError) { Log.i(TAG, "PlacementId:" + placementId + ": onInterstitialAutoLoadFail:\n" + adError.getFullErrorInfo()); } }; private final ATInterstitialAutoEventListener autoCpEventListener = new ATInterstitialAutoEventListener() { @Override public void onInterstitialAdClicked(ATAdInfo adInfo) { Log.i(TAG, "onInterstitialAdClicked:" + adInfo.toString()); } @Override public void onInterstitialAdShow(ATAdInfo adInfo) { Log.i(TAG, "onInterstitialAdShow1111111111:" + adInfo.toString()); MainActivity.reportInfo(adInfo); } @Override public void onInterstitialAdClose(ATAdInfo adInfo) { Log.i(TAG, "onInterstitialAdClose:" + adInfo.toString()); } @Override public void onInterstitialAdVideoStart(ATAdInfo adInfo) { Log.i(TAG, "onInterstitialAdVideoStart:" + adInfo.toString()); } @Override public void onInterstitialAdVideoEnd(ATAdInfo adInfo) { Log.i(TAG, "onInterstitialAdVideoEnd:" + adInfo.toString()); } @Override public void onInterstitialAdVideoError(AdError adError) { Log.i(TAG, "onInterstitialAdVideoError:" + adError.getFullErrorInfo()); } public void onDeeplinkCallback(ATAdInfo adInfo, boolean isSuccess) { Log.i(TAG, "onDeeplinkCallback:\n" + adInfo.toString() + "| isSuccess:" + isSuccess); } public void onDownloadConfirm(Context context, ATAdInfo adInfo, ATNetworkConfirmInfo networkConfirmInfo) { Log.i(TAG, "onDownloadConfirm:\n" + adInfo.toString()); } }; private void initCpInterstitialAd() { mInterstitialAd = new ATInterstitial(mContext, LCAppcation.interstitialAdId); mInterstitialAd.setAdRevenueListener(new BaseActivity.AdRevenueListenerImpl()); mInterstitialAd.setAdListener(new ATInterstitialExListener() { @Override public void onDeeplinkCallback(ATAdInfo adInfo, boolean isSuccess) { Log.i(TAG, "onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess); } @Override public void onDownloadConfirm(Context context, ATAdInfo adInfo, ATNetworkConfirmInfo networkConfirmInfo) { Log.i(TAG, "onDownloadConfirm: adInfo=" + adInfo.toString()); } @Override public void onInterstitialAdLoaded() { Log.i(TAG, "onInterstitialAdLoaded"); } @Override public void onInterstitialAdLoadFail(AdError adError) { Log.i(TAG, "onInterstitialAdLoadFail:\n" + adError.getFullErrorInfo()); } @Override public void onInterstitialAdClicked(ATAdInfo entity) { Log.i(TAG, "onInterstitialAdClicked:\n" + entity.toString()); } @Override public void onInterstitialAdShow(ATAdInfo entity) { Log.i(TAG, "onInterstitialAdShow:\n" + entity.toString()); } @Override public void onInterstitialAdClose(ATAdInfo entity) { Log.i(TAG, "onInterstitialAdClose:\n" + entity.toString()); } @Override public void onInterstitialAdVideoStart(ATAdInfo entity) { Log.i(TAG, "onInterstitialAdVideoStart:\n" + entity.toString()); } @Override public void onInterstitialAdVideoEnd(ATAdInfo entity) { Log.i(TAG, "onInterstitialAdVideoEnd:\n" + entity.toString()); } @Override public void onInterstitialAdVideoError(AdError adError) { Log.i(TAG, "onInterstitialAdVideoError:\n" + adError.getFullErrorInfo()); } }); mInterstitialAd.setAdSourceStatusListener(new BaseActivity.ATAdSourceStatusListenerImpl()); } private void initCpAutoLoad() { ATInterstitialAutoAd.init(mContext, null, autoCpLoadListener); String curPlacementId = LCAppcation.interstitialAdId; mCpAutoLoadPlacementIdMap.put(curPlacementId, true); ATInterstitialAutoAd.addPlacementId(curPlacementId); } private ATShowConfig getCpATShowConfig() { ATShowConfig.Builder builder = new ATShowConfig.Builder(); builder.scenarioId(AdConst.SCENARIO_ID.INTERSTITIAL_AD_SCENARIO); builder.showCustomExt(AdConst.SHOW_CUSTOM_EXT.INTERSTITIAL_AD_SHOW_CUSTOM_EXT); return builder.build(); } private void loadCpAd() { SDKUtil.initSDK(mContext); if (mInterstitialAd == null) { return; } Map<String, Object> localMap = new HashMap<>(); // localMap.put(ATAdConst.KEY.AD_WIDTH, getResources().getDisplayMetrics().widthPixels); // localMap.put(ATAdConst.KEY.AD_HEIGHT, getResources().getDisplayMetrics().heightPixels); //插屏广告使用原生自渲染广告时,设置自定义渲染方式:只需要在发起请求时额外设置setNativeAdCustomRender即可,请求、展示广告流程同插屏广告接入流程相同。 mInterstitialAd.setNativeAdCustomRender(new BaseActivity.NativeAdCustomRender(mContext)); mInterstitialAd.setLocalExtra(localMap); mInterstitialAd.load(); } private void isCpAdReady() { ATInterstitialAutoAd.isAdReady(LCAppcation.interstitialAdId); } private void showCpAd() { ATInterstitialAutoAd.show(getActivity(), LCAppcation.interstitialAdId, getCpATShowConfig(), autoCpEventListener, new BaseActivity.AdRevenueListenerImpl()); } private ATShowConfig getYsATShowConfig() { ATShowConfig.Builder builder = new ATShowConfig.Builder(); builder.scenarioId(AdConst.SCENARIO_ID.NATIVE_AD_SCENARIO); builder.showCustomExt(AdConst.SHOW_CUSTOM_EXT.NATIVE_AD_SHOW_CUSTOM_EXT); return builder.build(); } private void initYsATNativeAd(String placementId) { mATNative = new ATNative(getActivity(), placementId, new ATNativeNetworkListener() { @Override public void onNativeAdLoaded() { printLogOnUI("onNativeAdLoaded load success..."); } @Override public void onNativeAdLoadFail(AdError adError) { printLogOnUI("onNativeAdLoadFail load fail...:" + adError.getFullErrorInfo()); } }); mATNative.setAdSourceStatusListener(new BaseActivity.ATAdSourceStatusListenerImpl()); } private void loadYsAd(int adViewWidth, int adViewHeight) { SDKUtil.initSDK(getActivity()); printLogOnUI(getString(R.string.anythink_ad_status_loading)); Map<String, Object> localExtra = new HashMap<>(); localExtra.put(ATAdConst.KEY.AD_WIDTH, adViewWidth); localExtra.put(ATAdConst.KEY.AD_HEIGHT, adViewHeight); mATNative.setLocalExtra(localExtra); mATNative.makeAdRequest(); } private boolean isYsAdReady() { boolean isReady = mATNative.checkAdStatus().isReady(); printLogOnUI("isAdReady:" + isReady); List<ATAdInfo> atAdInfoList = mATNative.checkValidAdCaches(); Log.i(TAG, "Valid Cahce size:" + (atAdInfoList != null ? atAdInfoList.size() : 0)); if (atAdInfoList != null) { for (ATAdInfo adInfo : atAdInfoList) { Log.i(TAG, "\nCahce detail:" + adInfo.toString()); } } return isReady; } private void showYsAd() { // NativeAd nativeAd = mATNative.getNativeAd(); NativeAd nativeAd = mATNative.getNativeAd(getYsATShowConfig()); if (nativeAd != null) { if (mNativeAd != null) { mNativeAd.destory(); } mNativeAd = nativeAd; mNativeAd.setAdRevenueListener(new BaseActivity.AdRevenueListenerImpl()); mNativeAd.setNativeEventListener(new ATNativeEventExListener() { @Override public void onDeeplinkCallback(ATNativeAdView view, ATAdInfo adInfo, boolean isSuccess) { printLogOnUI("onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess); } @Override public void onAdImpressed(ATNativeAdView view, ATAdInfo entity) { printLogOnUI("native ad onAdImpressed:\n" + entity.toString()); MainActivity.reportInfo(entity); } @Override public void onAdClicked(ATNativeAdView view, ATAdInfo entity) { printLogOnUI("native ad onAdClicked:\n" + entity.toString()); } @Override public void onAdVideoStart(ATNativeAdView view) { printLogOnUI("onAdVideoStart"); } @Override public void onAdVideoEnd(ATNativeAdView view) { printLogOnUI("onAdVideoEnd"); } @Override public void onAdVideoProgress(ATNativeAdView view, int progress) { printLogOnUI("onAdVideoProgress"); } }); mNativeAd.setDislikeCallbackListener(new ATNativeDislikeListener() { @Override public void onAdCloseButtonClick(ATNativeAdView view, ATAdInfo entity) { printLogOnUI("native ad onAdCloseButtonClick"); exitYsNativePanel(); } }); mWoDeATNativeView.removeAllViews(); ATNativePrepareInfo mNativePrepareInfo = null; try { mNativePrepareInfo = new ATNativePrepareExInfo(); //bindTTDislikeDialog(mATNativeView, mNativeAd); if (mNativeAd.isNativeExpress()) { mNativeAd.renderAdContainer(mWoDeATNativeView, null); } else { SelfRenderViewUtil.bindSelfRenderView(getActivity(), mNativeAd.getAdMaterial(), mWoDeSelfRenderView, mNativePrepareInfo); mNativeAd.renderAdContainer(mWoDeATNativeView, mWoDeSelfRenderView); } } catch (Exception e) { e.printStackTrace(); } //下载类原生自渲染广告设置下载状态监听,更新CTA按钮文案 if (!mNativeAd.isNativeExpress() && mNativeAd.getAdMaterial() .getNativeAdInteractionType() == NativeAdInteractionType.APP_DOWNLOAD_TYPE && mNativePrepareInfo.getCtaView() != null && mNativePrepareInfo.getCtaView() instanceof TextView) { TextView ctaTextView = (TextView) mNativePrepareInfo.getCtaView(); mNativeAd.setAdDownloadListener(new ATAppDownloadListener() { @Override public void onDownloadStart(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("暂停下载"); printLogOnUI("onDownloadStart totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName); } }); } @Override public void onDownloadUpdate(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("暂停下载"); printLogOnUI("onDownloadUpdate totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName); } }); } @Override public void onDownloadPause(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("恢复下载"); printLogOnUI("onDownloadPause totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName); } }); } @Override public void onDownloadFinish(ATAdInfo adInfo, long totalBytes, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("立即安装"); printLogOnUI("onDownloadFinish totalBytes:" + totalBytes + ",appName:" + appName); } }); } @Override public void onDownloadFail(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("开始下载"); printLogOnUI("onDownloadFail totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName); } }); } @Override public void onInstalled(ATAdInfo adInfo, String fileName, String appName) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ctaTextView.setText("打开应用"); printLogOnUI("onInstalled appName:" + appName); } }); } }); } mNativeAd.prepare(mWoDeATNativeView, mNativePrepareInfo); mWoDeATNativeView.setVisibility(View.VISIBLE); } else { printLogOnUI("this placement no cache!"); } } protected void printLogOnUI(String msg) { // Log.i(TAG,msg); } } 这个if (remindedList.isEmpty()) { Toast.makeText(context, "暂无提醒中的快递", Toast.LENGTH_SHORT).show(); } else { Log.d("RemindFragment", "显示 " + remindedList.size() + " 个提醒项"); }提示吐司会弹好几遍
11-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值