Code samples

On this page, you'll find additional code examples referenced in the magazine, gathered together in one place, organised by page number. These are generally the longer or trickier examples that we couldn't fit on the page. For other snippets of code, you'll find the information on the chapter pages, which you can access from the panel at the left.

Note: in some cases, the screen layout may appear to cut off the right hand edge of some of the lines of code. Just select all the code in your browser and copy it - when you past it into B4A or another app, the code will be complete. In some browsers, clicking three times quickly in the code will automatically select it all.

Page 124: Sharing scores

To share a short piece of text, we use this code, in the click handler for our 'share' button:

Dim sharer As Intent
sharer.Initialize(sharer.ACTION_SEND,"")
sharer.SetType("text/plain")
sharer.PutExtra("android.intent.extra.TEXT", "I just scored " & Main.score & " in #TypeAttack")
sharer.WrapAsIntentChooser("Share your high score via")
StartActivity(sharer)

This code is based on an entry in the B4A Wiki, itself based on a post by forum user agraham. The code is modified here, firstly so that the same name is always use for our screenshot of the game, and secondly to fill the background with black. as otherwise it  may appear transparent, which can be tricky to view. Add this code to your main app, and make sure that the save_screen sub is called, before you start the High Scores activity.

Sub save_screen
	' save the current screen at the end of the game
	' we can share it from the high scores page
	' code from the B4A Wiki at http://www.basic4ppc.com/android/wiki/index.php/Tricks_Of_The_Trade#Getting_a_Screenshot_Programmatically
	' we delete the file if an old one exists

	If File.Exists(File.DirRootExternal, "TypeAttacklastgame.png")= False OR File.Delete( File.DirRootExternal, "TypeAttacklastgame.png") Then
		Dim Obj1, Obj2 As Reflector
	    Dim bmp As Bitmap
	    Dim c As Canvas
	    Obj1.Target = Obj1.GetActivityBA
	    Obj1.Target = Obj1.GetField("vg")
	    bmp.InitializeMutable(Activity.Width, Activity.Height)
	    c.Initialize2(bmp)
		
		' put a black background in place
		c.DrawColor(Colors.Black)
		
	    Dim args(1) As Object
	    Dim types(1) As String
	    Obj2.Target = c
	    Obj2.Target = Obj2.GetField("canvas")
	    args(0) = Obj2.Target
	    types(0) = "android.graphics.Canvas"
	    Obj1.RunMethod4("draw", args, types)
	    Dim Out As OutputStream
	    Out = File.OpenOutput(File.DirRootExternal, "TypeAttacklastgame.png", False)
	    bmp.WriteToStream(Out, 100, "PNG")
	    Out.Close
	End If
End Sub

Now, to share the image of the screen, this code can be added to the LongClick sub for the share button:

' share the score with a picture of the screen
If File.Exists(File.DirRootExternal,"TypeAttacklastgame.png") Then
    Dim sharer As MESShareLibrary
    sharer.sharebinary("file://" & File.DirRootExternal & "/TypeAttacklastgame.png","image/png","Share your last game on","I just scored " & Main.score & " in #TypeAttack")
End If

Page 142: Adding adverts to your app

Although fairly straightforward, there are some extra configuration steps you need to perform in this workshop to make the AdMob library perform. Assuming you installed the Android SDK in C:\Android, as in our example right at the start of the magazine, right click this link and copy it into the address bar of an Explorer window to open the folder containing the play_services.jar file, then copy it to your B4A Additional Libraries folder.

You need to copy this line to the Project Attributes section of your code, again, assuming you installed the Java tools in C:\Android:

#AdditionalRes: C:\android\android-sdk\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms

And the following code needs to be copied and pasted into your app's Manifest:

'AdMob
AddApplicationText(
<meta-data android:name="com.google.android.gms.version"
  android:value="@integer/google_play_services_version"/>
 <activity android:name="com.google.android.gms.ads.AdActivity"
  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
)
'End of AdMob

Declare the AdView in the Globals section of your code, like this

Dim advert As AdView

And add it to your app with code like this, which places the add centered horizontally, 2dip above the bottom of the screen. Obviously, replace "yourAdUnitIdHere" with the id code displayed on the AdMob page:

advert.Initialize("Ad","yourAdUnitIdHere")
Activity.AddView(advert,(100%x-320dip)/2,100%y-52dip, 320dip,50dip)
advert.LoadAd

The code to deal with AdMob events looks like this (borrowed from the B4A forums):

Sub Ad_FailedToReceiveAd (ErrorCode As String)
    Log("failed: " & ErrorCode)
End Sub
Sub Ad_ReceiveAd
    Log("received")
End Sub
Sub Ad_AdScreenDismissed
   Log("screen dismissed")
End Sub