Development of first-screen ads (Android)

Source: Internet
Author: User

Development of first-screen ads (Android)

As a mature application, there must be advertisements. How can we develop advertisements elegantly? Pay attention to some details.
This article provides a simple example. The code is for reference only.

Requirements:

Specifically
1. display the advertisement images stored locally, click the images, jump to the ad link, and provide the sharing function.
2. Download ad information asynchronously to increase the startup speed. Download and save ads and share images asynchronously to increase the loading speed.

Some tips are used during the development process. I will explain the points of attention in detail, including:
(1) Use the RxAndroid library to asynchronously download advertisement information on the new thread.
(2) Use the Picasso library to asynchronously download the image (Bitmap) and store it locally.
(3) use the native Handler class to implement the timer function and jump to a number in seconds.
(4) use the WebView view to load ad links and provide the sharing function.

1. Download Advertisement

On the welcome page, start an asynchronous thread, load advertisement information, increase the startup speed, and prevent switching from freezing due to slow network speed.

// Asynchronous ad information private void AsyncCheckInfo () {// asynchronous thread processing listener, which listens on the new thread and sends it to the active thread Observable
  
   
Observable = Observable. create (new Observable. OnSubscribe
   
    
() {@ Override public void call (Subscriber
    Subscriber) {subscriber. onNext (checkInfo (); subscriber. onCompleted ();}}). subscribeOn (Schedulers. newThread ()). observeOn (AndroidSchedulers. mainThread (); // callback observable successfully. subscribe (new Subscriber
    
     
() {@ Override public void onCompleted () {Log. I (TAG, "onCompleted") ;}@ Override public void onError (Throwable e) {}@ Override public void onNext (String s) {Log. I (TAG, "onNext ");}});}
    
   
  

Load in the new thread (newThread) and send it to the main thread (mainThread) after completion. Refer.

Judge the network and load advertisement information when there is a network. When there is no network, skip it directly.

// Load the Advertisement Information public String checkInfo () {if (NetUtils. isNetworkConnected (ChunyuApp. getAppContext () {UpdateUtils. checkDailyInfo (WelcomeActivity. this, mDailyRequestCallback); return "Begin to load info. ";}else {return" Stop to load info ";}}

InUpdateUtils.checkDailyInfo. If the ad information is included, it is stored in the preference (SharedPreference), and the next time the ad is started to read directly. If the ad information is not included, no data tag is set and no advertisement is determined during use.
Finally, call the callback interface.mDailyRequestCallbackContinue processing.

ArrayList adverts = version. advert; if (adverts. size ()> 0) {for (int I = 0; I <adverts. size (); ++ I) {Advert advert = adverts. get (I); if (advert. number = 1) {// Number equal to 0 is the advertisement PedometerAdManager. getInstance (). init (advert) ;}}} else {Log. e (TAG, "ad is empty"); SharedPreferences sp = PreferenceManager. getdefasharsharedpreferences (ChunyuApp. getAppContext (); sp. edit (). putBoolean (WelcomeActivity. FIRST_AD_IS_HAVE_PREFS, false ). apply ();}
2. store images

After the advertisement information is stored, you can obtain the image download link. To increase the display speed, the downloaded image is stored locally. because downloading is a network request and requires asynchronous processing, this article uses the Picasso library and has not invented the wheel.

// Daily message callback private final UpdateUtils. DailyRequestCallback callback = new UpdateUtils. DailyRequestCallback () {@ Override public void operationExecutedSuccess () {if (mAdManager. getImageUrl ()! = Null &&! MAdManager. getImageUrl (). isEmpty () Picasso. with (WelcomeActivity. this ). load (mAdManager. getImageUrl ()). into (mAdImageTarget); if (mAdManager. getaskicon ()! = Null &&! MAdManager. getaskicon (). isEmpty () Picasso. with (WelcomeActivity. this ). load (mAdManager. getaskicon ()). into (mademediimagetarget);} @ Override public void operationExecutedFailed () {Log. e (TAG, "operationExecutedFailed") ;}}; // ad image private Target mAdImageTarget = new Target () {@ Override public void onBitmapLoaded (Bitmap bitmap, Picasso. loadedFrom from) {String path = FileUtility. savePic (bitmap); mPrefs. edit (). putString (FIRST_AD_PATH_PREFS, path ). apply () ;}@ Override public void onBitmapFailed (Drawable errorDrawable) {}@ Override public void onPrepareLoad (Drawable placeHolderDrawable ){}}; // share Icon private Target mAdShareImageTarget = new Target () {@ Override public void onBitmapLoaded (Bitmap bitmap, Picasso. loadedFrom from) {String path = FileUtility. savePic (bitmap); mPrefs. edit (). putString (FIRST_AD_SHARE_IMAGE_URL_PREFS, path ). apply () ;}@ Override public void onBitmapFailed (Drawable errorDrawable) {}@ Override public void onPrepareLoad (Drawable placeHolderDrawable ){}};

When the page is paused, remove the Picasso request thread.

@ Override protected void onPause () {MobclickAgent. onPause (this); handler. removeCallbacks (runnable); // stop Picasso. with (this ). cancelRequest (mAdImageTarget); // stop Picasso. with (this ). cancelRequest (mademediimagetarget); // stop super. onPause ();}

Note:: In Picasso,TargetYes andImageView ControlWeak binding: The ImageView is destroyed when it is destroyed.ImageView Control, You must manually destroy the request, as shown inonPauseCancel.Otherwise, a download exception occurs.. Reference.

3. Display Advertisement

First, the Logo page is displayed.LOGO_TIMESecond, then judgeShow boot (first startup)OrShow ads.
Display ads use data stored in the preference (SharedPreference). images are parsed using local resources to increase the display speed.

// Display the startup information private void showLaunchInfo () {// display the main screen Logo new Handler () for a period of time (). postDelayed (this: showAdInfo, LOGO_TIME);} // display the advertisement information private void showAdInfo () {// determine whether there is an advertisement if (mPrefs. getBoolean (FIRST_AD_IS_HAVE_PREFS, false) {Log. e (TAG, "include ad"); String path = mPrefs. getString (FIRST_AD_PATH_PREFS, ""); if (! Path. isEmpty () {int time = mPrefs. getInt (FIRST_AD_TIME_PREFS, 0); Bitmap bitmap = BitmapFactory. decodeFile (path); Log. e (TAG, "time:" + time); showAdImage (bitmap, time); if (! NetUtils. isNetworkConnected (ChunyuApp. getAppContext () {mIvWebImage. setClickable (false) ;}} else {gotoOtherActivity ();}}

Display advertisement usageStorage Data of the last network request, Or it may beFor this network request, Mainly depends onLOGO_TIMETime, whether to download the startup information and store it locally.

4. Ad Timer

ProvideCountdown timerIn seconds.Skip buttonSkip the advertisement directly.

// Display the private void showAdImage (Bitmap bitmap, int time) {mIvWebImage. setVisibility (View. VISIBLE); mTvSkip. setVisibility (View. VISIBLE); mTvSkip. setOnClickListener (v-> gotoOtherActivity (); mIvBackground. setVisibility (View. INVISIBLE); mIvFirstLogo. setVisibility (View. INVISIBLE); mIvWebImage. setImageBitmap (bitmap); mAdTime = time + 2; handler. post (runnable); // set the second to read} // set the second to private int s = 0; // Time Delay private final Handler handler = new Handler (); private final Runnable runnable = new Runnable () {@ Override public void run () {// handler comes with a method to implement the timer try {handler. postDelayed (this, 1000); if (s <1) {s ++; return;} if (s <= (mAdTime-1) {mTvSkip. setText (String. valueOf ("Skip \ n" + Integer. toString (mAdTime-1)-(s ++) + "second");} // when the timer is 0, start to jump to if (s = mAdTime) {gotoOtherActivity () ;}} catch (Exception e) {e. printStackTrace ();}}};

The ad time is displayed for an additional two seconds. The page Jump Interval is provided. The second after the previous second ensures that the ad time is sufficient.

InAd page JumpOrPage endsDelete time callback.

// Jump to the actual advertisement View public void gotoShowAdView (view View) {NV. o (this, AdvertisementActivity. class); handler. removeCallbacks (runnable); finish ();}
@ Override protected void onPause () {MobclickAgent. onPause (this); handler. removeCallbacks (runnable); // stop Picasso. with (this ). cancelRequest (mAdImageTarget); // stop Picasso. with (this ). cancelRequest (mademediimagetarget); // stop super. onPause ();}

This document useshandlerClass, cyclic call timing, must be cleared when the page is leftrunnableCallback. Otherwise, the thread will be forgotten to leak the memory.

5. Link Page

Click the ad image to jump to the ad link. Set full screen or provide the sharing function based on the parameters to share the link. the title, content, and Icon are required for sharing. The image is pre-stored locally after being downloaded from the server.

/*** Advertising Activity *

* Created by wangchenlong on 15/12/2. */public class AdvertisementActivity extends PActivity {@ SuppressWarnings ("unused") private static final String TAG = "DEBUG-WCL:" + AdvertisementActivity. class. getSimpleName (); @ Bind (R. id. advertise_pwv_container) PedoWebView mPwvContainer; @ Bind (R. id. advertise_ll_back_home) LinearLayout mLlBackHome; @ Bind (R. id. advertise_ll_send_session) LinearLayout mLlSend Session; @ Bind (R. id. advertise_ll_send_timeline) LinearLayout mLlSendTimeline; @ Bind (R. id. advertise_ll_action_bar) LinearLayout mLlActionBar; private SharedPreferences mPrefs; private int mFlag; // determine the sharing location private static final int WECHAT_SESSION = 0; // private static final int WECHAT_TIMELINE = 1; // circle of friends @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceS Tate); setContentView (R. layout. activity_advertisement); ButterKnife. bind (this); mPrefs = PreferenceManager. getdefasharsharedpreferences (ChunyuApp. getAppContext (); ActionBar actionBar = getSupportActionBar (); if (actionBar! = Null) actionBar. setDisplayHomeAsUpEnabled (true); // whether to enable full screen if (mPrefs. getBoolean (WelcomeActivity. FIRST_AD_IS_FULL_PREFS, false) {mLlActionBar. setVisibility (View. GONE);} else {mLlBackHome. setOnClickListener (v-> {NV. o (this, PedometerActivity. class); finish () ;}); // whether to share if (mPrefs. getBoolean (WelcomeActivity. first_ad_is_pai_prefs, false) {mLlSendSession. setOnClickListener (v-> {mFlag = WEC HAT_SESSION; receivwechat () ;}); mLlSendTimeline. setOnClickListener (v-> {mFlag = WECHAT_TIMELINE; receivwechat () ;}) ;} else {mLlSendSession. setVisibility (View. GONE); mLlSendTimeline. setVisibility (View. GONE) ;}} mPwvContainer. loadUrl (mPrefs. getString (WelcomeActivity. FIRST_AD_URL_PREFS, "");} // share it with public void javaswechat () {IWXAPI wxapi = wxapifacloud. createWXAPI (ChunyuApp. getAppContext (), S NSConst. WX_APP_ID_ONLINE, true); wxapi. registerApp (SNSConst. WX_APP_ID_ONLINE); WXWebpageObject webpage = new WXWebpageObject (); webpage. webpageUrl = mPrefs. getString (WelcomeActivity. FIRST_AD_URL_PREFS, ""); WXMediaMessage msg = new WXMediaMessage (webpage); msg. title = mPrefs. getString (WelcomeActivity. FIRST_AD_SHARE_TITLE_PREFS, ""); msg. description = mPrefs. getString (WelcomeActivity. FIRST_AD_SHARE _ CONTENT_PREFS, ""); String path = mPrefs. getString (WelcomeActivity. FIRST_AD_SHARE_IMAGE_URL_PREFS, ""); if (! Path. isEmpty () {Bitmap bitmap = BitmapFactory. decodeFile (path); if (bitmap! = Null) {msg. setThumbImage (bitmap);} else {msg. setThumbImage (BitmapFactory. decodeResource (getResources (), R. drawable. icon);} SendMessageToWX. req req = new SendMessageToWX. req (); req. transaction = String. valueOf (System. currentTimeMillis (); req. message = msg; req. scene = (mFlag = 0 )? SendMessageToWX. req. WXSceneSession: SendMessageToWX. req. WXSceneTimeline); wxapi. sendReq (req) ;}}@ Override public void onBackPressed () {if (mPwvContainer. canGoBack () {mPwvContainer. goBack ();} else {NV. o (this, PedometerActivity. class); finish ();}}}

Call the back button (onBackPressed): When a webpage jumps to multiple pages, the previous page is returned. When the homepage is displayed, the advertisement page is exited and the homepage is redirected. the shared Icon (Icon). It is best to use a square full graph. Otherwise, the transparent part will be replaced by black. When providing images on the server, pay attention to it.

Final effect:

OK. Now that the development of the ad page is complete, you can make money! Enjoy It.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.