1. Preface
In the development of Android projects, there is often a need to launch page ads.Today I'll start the implementation of page advertisement in order to use it for reference in future projects.
2. Overview
Ideas for implementation: 1. During the initialization phase of the startup page, access the back-end interface to get advertising data, which is encapsulated in JavaBean. 2. Select a presentation method based on the type of advertisement in the returned data, such as static map, Gif motion map, or video. If the returned advertisement data is empty, it will jump to the main page directly after initializing the page resource. 3. Display the advertisement and start counting down the advertisement. Click Skip or end the countdown, then jump from the start page to the main page. As mentioned above, the third-party framework Glide is used in this paper.
3. Realization
Create a project, configure a manifest file, and remember to include the following permissions in the manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The key codes are as follows.
//Countdown Handler
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (time < 0) {
mAdShowStatus = true;
if (mHandler != null && mHandler.hasMessages(0)) {
mHandler.removeMessages(0);
}
enterToMain();
} else {
time = time - 1;
ad_time_tv.setText("skip" + time);
mHandler.sendEmptyMessageDelayed(0, 1000);
}
}
};
//Display Advertising
private void showAd(AdverBean bean) {
ad_time_tv.setVisibility(View.VISIBLE);
switch (bean.getAdvertType()) {
case Constant.IMAGE_TYPE://Image type
final WeakReference<ImageView> imageViewWeakReference1 = new WeakReference<>(ad_iv);
ImageView target1 = imageViewWeakReference1.get();
if (target1 != null) {
Glide.with(this)
.load(bean.getAdvertUrl())
.into(target1);
time = 3;
ad_time_tv.setText("skip" + time);
mHandler.sendEmptyMessageDelayed(0, 1000);
}
break;
case Constant.GIF_TYPE://GIF Type
final WeakReference<ImageView> imageViewWeakReference2 = new WeakReference<>(ad_iv);
ImageView target2 = imageViewWeakReference2.get();
if (target2!= null) {
Glide.with(this)
.load(bean.getAdvertUrl())
.into(target2);
time = 5;
ad_time_tv.setText("skip" + time);
mHandler.sendEmptyMessageDelayed(0, 1000);
}
break;
default:
mAdShowStatus = true;
enterToMain();
}
}