Java Question Wrapper for UnityAds problem

SSDM71

Active Member
Licensed User
Longtime User
I have a problem with a wrapper for UnityAds

Following there is my java code of the wrapper:
B4X:
package com.unity3d.ads.android.unity3d;

import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.BA;
import java.lang.reflect.Method;
import java.util.HashMap;
import android.app.Activity;
import com.unity3d.ads.android.UnityAds;
import com.unity3d.ads.android.UnityAdsDeviceLog;
import com.unity3d.ads.android.IUnityAdsListener;
import com.unity3d.ads.android.UnityAdsUtils;
import com.unity3d.ads.android.properties.UnityAdsProperties;
import com.unity3d.ads.android.webapp.UnityAdsWebData;
import com.unity3d.ads.android.zone.UnityAdsZoneManager;
@ShortName("UnityAdsWrapper")
public class UnityAdsWrapper implements IUnityAdsListener {
    private Activity _startupActivity = null;
    private String _gameObject = null;
    private String _gameId = null;
    private Method _sendMessageMethod = null;
    private boolean _testMode = false;
    private static Boolean _constructed = false;
    private static Boolean _initialized = false;

    public UnityAdsWrapper () {
        if (!_constructed) {
            _constructed = true;
            try {
                    Class<?> unityClass = Class.forName("com.unity3d.player.UnityPlayer");
                    Class<?> paramTypes[] = new Class[3];
                    paramTypes[0] = String.class;
                    paramTypes[1] = String.class;
                    paramTypes[2] = String.class;
                    _sendMessageMethod = unityClass.getDeclaredMethod("UnitySendMessage", paramTypes);
            }
            catch (Exception e) {
                UnityAdsDeviceLog.error("Error getting class or method of com.unity3d.player.UnityPlayer, method UnitySendMessage(string, string, string). " + e.getLocalizedMessage());
            }
        }
    }
    public boolean isSupported () {
        return UnityAds.isSupported();
    }
    public String getSDKVersion () {
        return UnityAds.getSDKVersion();
    }
    public void Initialize(final String gameId,BA ba, boolean testMode, String gameObject, final String unityVersion) {
        if (!_initialized) {
            _initialized = true;
            _gameId = gameId;
            _gameObject = gameObject;
            _testMode = testMode;
            if (_startupActivity == null)
                _startupActivity = ba.activity;
            final UnityAdsWrapper listener = this;

            try {
                UnityAdsUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UnityAds.setTestMode(_testMode);
            if(unityVersion.length() > 0) {
              UnityAdsProperties.UNITY_VERSION = unityVersion;
            }
                        UnityAds.init(_startupActivity, _gameId, listener);
                    }
                });
            }
            catch (Exception e) {
                UnityAdsDeviceLog.error("Error occured while initializing Unity Ads");
            }
        }
    }
    public boolean show (final String zoneId, final String rewardItemKey, final String optionsString) {
        if(canShowZone(zoneId)) {
            HashMap<String, Object> options = null;

            if(optionsString.length() > 0) {
                options = new HashMap<String, Object>();
                for(String rawOptionPair : optionsString.split(",")) {
                    String[] optionPair = rawOptionPair.split(":");
                    options.put(optionPair[0], optionPair[1]);
                }
            }

            if(rewardItemKey.length() > 0) {
                if(zoneId != null && zoneId.length() > 0) {
                    UnityAds.setZone(zoneId, rewardItemKey);
                }
            } else {
                if(zoneId != null && zoneId.length() > 0) {
                    UnityAds.setZone(zoneId);
                }
            }

            return UnityAds.show(options);
        }

        return false;
    }

    public void hide () {
        UnityAds.hide();
    }

    public boolean canShow () {
        return UnityAds.canShow();
    }

    public boolean canShowZone(String zone) {
        if(zone != null && zone.length() > 0) {
            UnityAdsZoneManager zoneManager = UnityAdsWebData.getZoneManager();
            if(zoneManager != null) {
                if(zoneManager.getZone(zone) != null) {
                    return UnityAds.canShow();
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

        return UnityAds.canShow();
    }

    public boolean hasMultipleRewardItems () {
        return UnityAds.hasMultipleRewardItems();
    }

    public String getRewardItemKeys () {
        if (UnityAds.getRewardItemKeys() == null) return null;
        if (UnityAds.getRewardItemKeys().size() > 0) {
            String keys = "";
            String key="";
            for (int i=0; i<UnityAds.getRewardItemKeys().size(); i++) {
                UnityAds.getRewardItemKeys().set(i, key);
                if (UnityAds.getRewardItemKeys().indexOf(key) > 0) {
                    keys += ";";
                }
                keys += key;
            }
            return keys;
        }

        return null;
    }

    public String getDefaultRewardItemKey () {
        return UnityAds.getDefaultRewardItemKey();
    }

    public String getCurrentRewardItemKey () {
        return UnityAds.getCurrentRewardItemKey();
    }

    public boolean setRewardItemKey (String rewardItemKey) {
        return UnityAds.setRewardItemKey(rewardItemKey);
    }

    public void setDefaultRewardItemAsRewardItem () {
        UnityAds.setDefaultRewardItemAsRewardItem();
    }

    public String getRewardItemDetailsWithKey (String rewardItemKey) {
        String retString = "";

        if (UnityAds.getRewardItemDetailsWithKey(rewardItemKey) != null) {
            UnityAdsDeviceLog.debug("Fetching reward data");

            @SuppressWarnings({ "unchecked", "rawtypes" })
            HashMap<String, String> rewardMap = (HashMap)UnityAds.getRewardItemDetailsWithKey(rewardItemKey);

            if (rewardMap != null) {
                retString = rewardMap.get(UnityAds.UNITY_ADS_REWARDITEM_NAME_KEY);
                retString += ";" + rewardMap.get(UnityAds.UNITY_ADS_REWARDITEM_PICTURE_KEY);
                return retString;
            }
            else {
                UnityAdsDeviceLog.debug("Problems getting reward item details");
            }
        }
        else {
            UnityAdsDeviceLog.debug("Could not find reward item details");
        }
        return "";
    }

    public String getRewardItemDetailsKeys () {
        return String.format("%s;%s", UnityAds.UNITY_ADS_REWARDITEM_NAME_KEY, UnityAds.UNITY_ADS_REWARDITEM_PICTURE_KEY);
    }

    public void setLogLevel(int logLevel) {
        UnityAdsDeviceLog.setLogLevel(logLevel);
    }

    public void enableUnityDeveloperInternalTestMode() {
        UnityAds.enableUnityDeveloperInternalTestMode();
    }

    public void setCampaignDataURL(String campaignDataURL) {
        UnityAds.setCampaignDataURL(campaignDataURL);
    }

    // IUnityAdsListener

    @Override
    public void onHide() {
        sendMessageToUnity3D("onHide", null);
    }

    @Override
    public void onShow() {
        sendMessageToUnity3D("onShow", null);
    }

    @Override
    public void onVideoStarted() {
        sendMessageToUnity3D("onVideoStarted", null);
    }

    @Override
    public void onVideoCompleted(String rewardItemKey, boolean skipped) {
        sendMessageToUnity3D("onVideoCompleted", rewardItemKey + ";" + (skipped ? "true" : "false"));
    }

    @Override
    public void onFetchCompleted() {
        sendMessageToUnity3D("onFetchCompleted", null);
    }

    @Override
    public void onFetchFailed() {
        sendMessageToUnity3D("onFetchFailed", null);
    }

    public void sendMessageToUnity3D(String methodName, String parameter) {
        // Unity Development build crashes if parameter is NULL
        if (parameter == null)
                parameter = "";

        if (_sendMessageMethod == null) {
            UnityAdsDeviceLog.error("Cannot send message to Unity3D. Method is null");
            return;
        }
        try {
            UnityAdsDeviceLog.debug("Sending message (" + methodName + ", " + parameter + ") to Unity3D");
            _sendMessageMethod.invoke(null, _gameObject, methodName, parameter);
        }
        catch (Exception e) {
            UnityAdsDeviceLog.error("Can't invoke UnitySendMessage method. Error = "  + e.getLocalizedMessage());
        }
    }

}

I compile Javadoc with BADoclet and I export as Jar this.
I add to Additional libraries folder the jar and xml file.

And with this code it give me an error during "compiling generated java code":
B4X:
Sub Process_Globals
   
End Sub

Sub Globals
    Dim b As Button
    Dim ua As UnityAdsWrapper
End Sub

Sub Activity_Create(FirstTime As Boolean)
    ua.Initialize("59593",False,"","1.4.7")
    b.Initialize("b")
    Activity.AddView(b,2%x,2%x,96%x,10%y)
End Sub
Sub b_Click
    b.Enabled=False
    ua.show("defaultZone",Null,"")
End Sub
Sub Activity_Resume
   
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
B4X:
B4A version: 5.02 (1)
Parsing code.    (0.00s)
Compiling code.    (0.02s)
Compiling layouts code.    (0.00s)
Generating R file.    (0.04s)
Compiling generated Java code.    Error
B4A line: 27
ua.Initialize(\
javac 1.8.0_25
src\b4a\example\main.java:343: error: cannot access IUnityAdsListener
mostCurrent._ua.Initialize("59593",processBA,anywheresoftware.b4a.keywords.Common.False,"","1.4.7");
               ^
  class file for com.unity3d.ads.android.IUnityAdsListener not found
1 error

Maybe Have i to copy Unity Ads SDK in libraries folder same as TapForTapWrapper and load with #AdditionalJar?
Which is my mistake?
 

SSDM71

Active Member
Licensed User
Longtime User
Thanks for reply,

Now I added this line:
B4X:
@DependsOn(values={"unity-ads"})

I copy unity-ads.jar in libraries folder.

But when I compile my program It give me this fantastic error:
B4X:
B4A version: 5.02 (1)
Parsing code.    (0.00s)
Compiling code.    (0.02s)
Compiling layouts code.    (0.00s)
Generating R file.    (0.04s)
Compiling generated Java code.    (0.92s)
Convert byte code - optimized dex.    Error
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)
    at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:472)
    at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
    at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
    at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
    at com.android.dx.command.dexer.Main.processClass(Main.java:665)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:634)
    at com.android.dx.command.dexer.Main.access$600(Main.java:78)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:572)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:596)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:498)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:264)
    at com.android.dx.command.dexer.Main.run(Main.java:230)
    at com.android.dx.command.dexer.Main.main(Main.java:199)
    at com.android.dx.command.Main.main(Main.java:103)
...while parsing com/unity3d/ads/android/unity3d/UnityAdsWrapper$1.class
1 error; aborting
Attached there is the unityads sdk, maybe the problem is in the jar file..

Have you any idea which is the error?

Thanks,
 

Attachments

  • unity-ads.jar
    140.3 KB · Views: 303

SSDM71

Active Member
Licensed User
Longtime User
Compiling with Java 7 it don't give me these error.

Now the code is this:
B4X:
package com.unity3d.ads.android.unity3d;

import anywheresoftware.b4a.BA.DependsOn;
import anywheresoftware.b4a.BA.Permissions;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.ActivityObject;
import anywheresoftware.b4a.BA.Events;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.BA.Author;
import anywheresoftware.b4a.BA.ActivityObject;
import anywheresoftware.b4a.BA.DontInheritEvents;
import anywheresoftware.b4a.objects.ViewWrapper;
import java.lang.reflect.Method;
import java.util.HashMap;

import android.app.Activity;

import com.unity3d.ads.android.UnityAds;
import com.unity3d.ads.android.UnityAdsDeviceLog;
import com.unity3d.ads.android.IUnityAdsListener;
import com.unity3d.ads.android.UnityAdsUtils;
import com.unity3d.ads.android.properties.UnityAdsProperties;
import com.unity3d.ads.android.webapp.UnityAdsWebData;
import com.unity3d.ads.android.zone.UnityAdsZoneManager;
@ShortName("UnityAdsWrapper")
@Events(values={"Hide", "Show","VideoStarted","VideoCompleted(rewardItemKey As String,Skipped As Boolean)","FetchCompleted","FetchFailed"})
@ActivityObject
@DependsOn(values={"unity-ads"})
@Permissions(values={"android.permission.INTERNET", "android.permission.ACCESS_NETWORK_STATE"})
public class UnityAdsWrapper implements IUnityAdsListener {
    private Activity _startupActivity = null;
    private String _gameObject = null;
    private String _gameId = null;
    private Method _sendMessageMethod = null;
    private boolean _testMode = false;
    private static Boolean _constructed = false;
    private static Boolean _initialized = false;
    private String EN = "";
    private BA myba;
    public static String UNITY_OPTIONS_GAMERSID_KEY = UnityAds.UNITY_ADS_OPTION_GAMERSID_KEY;
    public static String UNITY_OPTIONS_MUTEVIDEO = UnityAds.UNITY_ADS_OPTION_MUTE_VIDEO_SOUNDS;
    public static String UNITY_OPTIONS_NOOFFERSCREEN = UnityAds.UNITY_ADS_OPTION_NOOFFERSCREEN_KEY;
    public static String UNITY_OPTIONS_OPENANIMETED = UnityAds.UNITY_ADS_OPTION_OPENANIMATED_KEY;
    public static String UNITY_OPTIONS_VIDEOUSEDEVIDEOIENTATION = UnityAds.UNITY_ADS_OPTION_VIDEO_USES_DEVICE_ORIENTATION;
    public UnityAdsWrapper () {
        if (!_constructed) {
            _constructed = true;
            try {
                    Class<?> unityClass = Class.forName("com.unity3d.player.UnityPlayer");
                    Class<?> paramTypes[] = new Class[3];
                    paramTypes[0] = String.class;
                    paramTypes[1] = String.class;
                    paramTypes[2] = String.class;
                    _sendMessageMethod = unityClass.getDeclaredMethod("UnitySendMessage", paramTypes);
            }
            catch (Exception e) {
                UnityAdsDeviceLog.error("Error getting class or method of com.unity3d.player.UnityPlayer, method UnitySendMessage(string, string, string). " + e.getLocalizedMessage());
            }
        }
    }


    // Public methods
    /**
     * @return Get if UnityAds is supported
     */
    public boolean isSupported () {
        return UnityAds.isSupported();
    }
    /**
     * @return Get the SDK Version
     */
    public String getSDKVersion () {
        return UnityAds.getSDKVersion();
    }
 
    public void Initialize(final String gameId,final BA ba, boolean testMode, String gameObject, final String unityVersion,String Eventname) {
        if (!_initialized) {
            EN=Eventname;
            _initialized = true;
            _gameId = gameId;
            _gameObject = gameObject;
            _testMode = testMode;
            myba=ba;
            if (_startupActivity == null)
                _startupActivity = ba.activity;
            final UnityAdsWrapper listener = this;
            try {
                UnityAdsUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UnityAds.setTestMode(_testMode);
                        if(unityVersion.length() > 0) {
                          UnityAdsProperties.UNITY_VERSION = unityVersion;
                        }
                        UnityAds.init(_startupActivity, _gameId, listener);
                    }
                });
            }
            catch (Exception e) {
                UnityAdsDeviceLog.error("Error occured while initializing Unity Ads");
            }
        }
     
    }
    public boolean show (final String zoneId, final String rewardItemKey, final String optionsString) {
        if(canShowZone(zoneId)) {
            HashMap<String, Object> options = null;

            if(optionsString.length() > 0) {
                options = new HashMap<String, Object>();
                for(String rawOptionPair : optionsString.split(",")) {
                    String[] optionPair = rawOptionPair.split(":");
                    options.put(optionPair[0], optionPair[1]);
                }
            }

            if(rewardItemKey.length() > 0) {
                if(zoneId != null && zoneId.length() > 0) {
                    UnityAds.setZone(zoneId, rewardItemKey);
                }
            } else {
                if(zoneId != null && zoneId.length() > 0) {
                    UnityAds.setZone(zoneId);
                }
            }

            return UnityAds.show(options);
        }

        return false;
    }
    public void setDebugMode(Boolean Active){
        UnityAds.setDebugMode(Active);
    }
    /**
     * @return Get the SDK Version to initialize the object
     */
    public String GetSDKVersion(){
        return UnityAds.getSDKVersion();
    }
    public void hide () {
        UnityAds.hide();
    }

    public boolean canShow () {
        return UnityAds.canShow();
    }

    public boolean canShowZone(String zone) {
        if(zone != null && zone.length() > 0) {
            UnityAdsZoneManager zoneManager = UnityAdsWebData.getZoneManager();
            if(zoneManager != null) {
                if(zoneManager.getZone(zone) != null) {
                    return UnityAds.canShow();
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

        return UnityAds.canShow();
    }

    public boolean hasMultipleRewardItems () {
        return UnityAds.hasMultipleRewardItems();
    }

    public String getRewardItemKeys () {
        if (UnityAds.getRewardItemKeys() == null) return null;
        if (UnityAds.getRewardItemKeys().size() > 0) {
            String keys = "";
            String key="";
            for (int i=0; i<UnityAds.getRewardItemKeys().size(); i++) {
                UnityAds.getRewardItemKeys().set(i, key);
                if (UnityAds.getRewardItemKeys().indexOf(key) > 0) {
                    keys += ";";
                }
                keys += key;
            }
            return keys;
        }

        return null;
    }

    public String getDefaultRewardItemKey () {
        return UnityAds.getDefaultRewardItemKey();
    }

    public String getCurrentRewardItemKey () {
        return UnityAds.getCurrentRewardItemKey();
    }

    public boolean setRewardItemKey (String rewardItemKey) {
        return UnityAds.setRewardItemKey(rewardItemKey);
    }

    public void setDefaultRewardItemAsRewardItem () {
        UnityAds.setDefaultRewardItemAsRewardItem();
    }

    public String getRewardItemDetailsWithKey (String rewardItemKey) {
        String retString = "";

        if (UnityAds.getRewardItemDetailsWithKey(rewardItemKey) != null) {
            UnityAdsDeviceLog.debug("Fetching reward data");

            @SuppressWarnings({ "unchecked", "rawtypes" })
            HashMap<String, String> rewardMap = (HashMap)UnityAds.getRewardItemDetailsWithKey(rewardItemKey);

            if (rewardMap != null) {
                retString = rewardMap.get(UnityAds.UNITY_ADS_REWARDITEM_NAME_KEY);
                retString += ";" + rewardMap.get(UnityAds.UNITY_ADS_REWARDITEM_PICTURE_KEY);
                return retString;
            }
            else {
                UnityAdsDeviceLog.debug("Problems getting reward item details");
            }
        }
        else {
            UnityAdsDeviceLog.debug("Could not find reward item details");
        }
        return "";
    }

    public String getRewardItemDetailsKeys () {
        return String.format("%s;%s", UnityAds.UNITY_ADS_REWARDITEM_NAME_KEY, UnityAds.UNITY_ADS_REWARDITEM_PICTURE_KEY);
    }

    public void setLogLevel(int logLevel) {
        UnityAdsDeviceLog.setLogLevel(logLevel);
    }

    public void enableUnityDeveloperInternalTestMode() {
        UnityAds.enableUnityDeveloperInternalTestMode();
    }

    public void setCampaignDataURL(String campaignDataURL) {
        UnityAds.setCampaignDataURL(campaignDataURL);
    }

    // IUnityAdsListener

    @Override
    public void onHide() {
        if (myba.subExists(EN + "_Hide")){
            myba.raiseEvent(myba.getSender(), EN + "_Hide","");
        }
        sendMessageToUnity3D("onHide", null);
    }

    @Override
    public void onShow() {
        if (myba.subExists(EN + "_Show")){
            myba.raiseEvent(myba.getSender(), EN + "_Show","");
        }
        sendMessageToUnity3D("onShow", null);
    }

    @Override
    public void onVideoStarted() {
        if (myba.subExists(EN + "_VideoStarted")){
            myba.raiseEvent(myba.getSender(), EN + "_VideoStarted","");
        }
        sendMessageToUnity3D("onVideoStarted", null);
    }

    @SuppressWarnings("null")
    @Override
    public void onVideoCompleted(String rewardItemKey, boolean skipped) {
        if (myba.subExists(EN + "_Hide")){
            Object par[] = null;
            par[0]=rewardItemKey;
            par[1]=skipped;
            myba.raiseEvent(myba.getSender(), EN + "_VideoCompleted",par);
        }
        sendMessageToUnity3D("onVideoCompleted", rewardItemKey + ";" + (skipped ? "true" : "false"));
    }

    @Override
    public void onFetchCompleted() {
        if (myba.subExists(EN + "_FetchCompleted")){
            myba.raiseEvent(myba.getSender(), EN + "_FetchCompleted","");
        }
        sendMessageToUnity3D("onFetchCompleted", null);
    }

    @Override
    public void onFetchFailed() {
        if (myba.subExists(EN + "_FetchFailed")){
            myba.raiseEvent(myba.getSender(), EN + "_FetchFailed","");
        }
        sendMessageToUnity3D("onFetchFailed", null);
    }

    public void sendMessageToUnity3D(String methodName, String parameter) {
        // Unity Development build crashes if parameter is NULL
        if (parameter == null)
                parameter = "";

        if (_sendMessageMethod == null) {
            UnityAdsDeviceLog.error("Cannot send message to Unity3D. Method is null");
            return;
        }
        try {
            UnityAdsDeviceLog.debug("Sending message (" + methodName + ", " + parameter + ") to Unity3D");
            _sendMessageMethod.invoke(null, _gameObject, methodName, parameter);
        }
        catch (Exception e) {
            UnityAdsDeviceLog.error("Can't invoke UnitySendMessage method. Error = "  + e.getLocalizedMessage());
        }
    }

}

It does't see the Ads. Have I to do anything similar to this?
Any idea?

Thanks,
 

walterf25

Expert
Licensed User
Longtime User
I think you're going about the wrong way doing this, i think you are complicating things way too much, half of the code you have here you really don't need, take a look at the example they provide for Android.
https://github.com/Applifier/unity-...ndroid/example/UnityAdsTestStartActivity.java

Good luck!
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…