Android API

Issues with this document? Submit a pull request to the website repository please.

Downloading the API

You can either download the zip or if you're a git user clone the repository.

Initializing the API

Before using the API you must initialize it with your public and private keys. Your keys need to be created in your database.

Playtomic.initialize(String publickey, String privatekey, String apiurl);

Your apiurl will be in the format http://your-application-name.herokuapp.com/ or similar.

If you are testing with the server running on your local computer use your lan address, 127.0.0.1 is the emulator's localhost.

To import the packages in your game copy the 'com' folder to your project and in your class:

import com.playtomic.android.*;

Examples

Each API has an extensive test library in the source code that demonstrates how to use every part in a variety of ways.

Newsletter subscription

Please note this requires additional setup you can read about here.

You can subscribe players to your newsletter mailinglist. By default this uses double-opt in so when a player registers for it they are sent an email and then confirm their intention.

You can collect additional data with your subscriptions but you must set it up first at MailChimp.

Playtomic.Newsletter.subscribe(NewsletterSubscription options, NewsletterSubscribeHandler callback);

NewsletterSubscription (extends JSONObject)

Property Setter Description
setEmail String The player's email address
setFirstName String The player's first name
setLastName String The player's last name
setField(String name, Object value) Void Sets a MERGE tag name and value defined in your MailChimp list.

Subscribing a player

NewsletterSubscription subscription = new NewsletterSubscription();
subscription.setEmail("test@exampleuri.com");
subscription.setFirstName("fred");
subscription.setLastName("bloggs");
subscription.setField("FIRSTPLAYED ", today)
subscription.setField("PLATFORM", "android");
subscription.setField("GAMEVERSION", 1.08);
subscription.setField("RESOLUTION", "800x400");

// note that these example MERGE fields must be created in your MailChimp
// dashboard, they do not exist by default.

Playtomic.Newsletters.subscribe(playerinfo, new NewsletterSubscribeHandler() {
    @Override
    public void onSuccess(PResponse r) {
    }

    @Override
    public void onFailure(PResponse response) {
	    // Request failed because of response.getErrorMessage()
    }
});

Achievements

The Achievements API gives you two powerful ways to add social, cross-platform achievements to your game.

Achievements have to be configured in your database first in the 'achievements' collection with the structure:

{ achievement: "the name", achievementkey: "secret key used when awarding" }

You can include any additional properties you want and have them returned in your game such as image urls, descriptions etc.

PlayerAchievement (extends JSONObject)

Property Getter Setter Description
-- setPlayerName String The player name. This can be by the player or provided by any 3rd party
-- setPlayerId String Facebook or other userids, used for filtering by friends.
getAchievement setAchievement String The name of the achievement.
-- setSource String The website or device the score occurred on
-- setFields Hashtable Any additional data you want to (or have) attached to an achievement like difficulty - that would mean for each achievement you automatically have 'easy', 'normal', 'hard' and can differentiate between them when retrieving the achievements.
setField(String, Object) void Sets a field without having to initialize the hashtable etc manually.
Properties set by the API server
getPlayer -- PlayerAward When listing if a playerid is provided their details are included here when they have the achievement
getFriends -- ArrayList<PlayerAward> When listing if a friendslist is provided any friends who have the achievement are included in this collection.
Saving details
-- setAchievementKey String The secret key used when saving achievements by players
-- setOverwrite Boolean If the player already has the achievement save over it
-- setAllowDuplicate Boolean If the player already has the achievement give it again

Saving achievements

To save an achievement you must know the achievement name and key and they must match what you configure in your database. This means if you want you can provide separate keys for each achievement so players can't easily cheat.

Playtomic.Achievements.save(achievement, callback);

A full example:

var achievement = new PlayerAchievement();
achievement.setAchievement("Punched Tass");
achievement.setAchievementKey("abcdefgh");
achievement.setPlayerId("1");
achievement.setPlayerName("ben");
achievement.setField("difficulty", "easy");

Playtomic.Achievements.save(achievement, new AchievementSaveHandler() {
    @Override
    public void onSuccess(PResponse r) {
    }

    @Override
    public void onFailure(PResponse response) {
	    // Request failed because of response.getErrorMessage()
    }
});

Listing achievements

Achievement lists can be requested that include just the achievement information or also incorporate the player and friends.

Playtomic.Achievements.list(options, callback);

Listing options

Property Type Description
playerid String Facebook or other userids, used for filtering by friends.
friendslist ArrayList Friends' playerids
filters Hashtable Any additional filtering information from the 'fields'

Some examples:

// just the achievements
Playtomic.Achievements.list(null, new AchievementListHandler() {
    @Override
    public void onSuccess(ArrayList<PlayerAchievement> achievements, PResponse r) {
      for(var i=0; i<achievements.length(); i++) {
        Log.d("Playtomic", achievements.get(i).toString());
        // will output { achievement: "Punched Tass" }
      }
    }

    @Override
    public void onFailure(PResponse response) {
    // Request failed because of response.getErrorMessage()
    }
});

// my friends and i
JSONArray friends = new JSONArray();
friends.put("2");
friends.put("3");
friends.put("4");
friends.put("5");

ListOptions options = new ListOptions();
options.set("playerid", "1");
options.set("friendslist", friends);

Playtomic.Achievements.list(options, new AchievementListHandler() {
    @Override
    public void onSuccess(ArrayList<PlayerAchievement> achievements, PResponse r) {
      for(var i=0; i<achievements.length(); i++) {
        Log.d("Playtomic", achievements.get(i).toString());
        //{
        //  achievement: "Punched Tass",
        //  player: {
        //    playerid: "1",
        //    playername: "ben",
        //    date: Date(),
        //    rdate: "Just now",
        //    fields: {
        //      difficulty: "easy"
        //    }
        //  },
        //  friends: [
        //    {
        //      // same as player object but for any friends with the achievement
        //    }
        //  ]
        //}
      }
    }

    @Override
    public void onFailure(PResponse response) {
    // Request failed because of response.getErrorMessage()
    }
});

Activity stream

You can also get achievements represented as an activity stream of each award.

Playtomic.Achievements.stream(options, callback);

Streaming options

Property Type Description
group Boolean If 'true' each person is only included once with their most recent award. If false it will include every award.
playerid String Facebook or other userids, used for filtering by friends.
friendslist JSONArray Friends' playerids
filters Hashtable Any additional filtering information from the 'fields'
page int Page number to return (default is 1)
perpage int Results per page (default is 20)
mode string today, last7days, last30days
source string Device or website if you save that information

PlayerAward (extends JSONObject)

When you 'stream' the messages are returned in this format. This is the same format used when you include player or friend information in 'list'.

playername String The player name. This can be by the player or provided by any 3rd party
playerid String Facebook or other userids, used for filtering by friends.
date Date The date of the the achievement was awarded
rdate String The relative date of the achievement was awarded eg "7 minutes ago"
source string Device or website if you save that information
fields Hashtable Any additional data you want to (or have) attached to an achievement like difficulty - that would mean for each achievement you automatically have 'easy', 'normal', 'hard' and can differentiate between them when retrieving the achievements.

Example streams

// show all the hard achievements by my friends and i as a stream
// my friends and i
JSONArray friends = new JSONArray();
friends.put("2");
friends.put("3");
friends.put("4");
friends.put("5");

ListOptions options = new ListOptions();
options.set("playerid", "1");
options.set("friendslist", friends);
options.set("group", true);
options.setFilterField("difficulty", "hard");

Playtomic.Achievements.stream(options, new AchievementStreamHandler() {
    @Override
    public void onSuccess(ArrayList<PlayerAchievement> achievements, int numachievements, PResponse r) {
      for(var i=0; i<achievements.length(); i++) {
        Log.d("Playtomic", achievements.get(i).toString());
          // {
          //  playerid: "1",
          //  playername: "ben",
          //  date: Date(),
          //  rdate: "Just now",
          //  fields: {
          //     difficulty: "hard" }
          //  },
          //  awarded: {
          //    achievement: "Punched tass"
          //  }
          // }

      }
    }

    @Override
    public void onFailure(PResponse response) {
    // Request failed because of response.getErrorMessage()
    }
});

Leaderboards

The Leaderboards API gives you very flexible high and low score leaderboards. They can be created in your game dynamically or set up in the edit leaderboards page.

Score structure

Getter Setter Type Description
getPlayerName setPlayerName String The player name. This can be by the player or provided by any 3rd party
getPlayerId setPlayerId String Facebook or other userids, used for filtering by friends.
getPoints setPoints long The player's score
getSource setSource String The website or device the score occurred on
getFields -- JSONObject Any additional data you want to (or have) attached to a score.
setField(String, Object) void Attach a property and value to your custom fields.
Properties set by the API server
getDate -- Date The date of the score
getRDate -- String The relative date of the score eg "7 minutes ago"
getRank -- int The rank based on your listing parameters.
Table detais
-- setTable String The name of the score table
-- setHighest Boolean The sort ordering by highest or lowest
-- setAllowDuplicates Boolean Create duplicates, or override or reject scores if they're not the best

Submitting scores

Score submission is handled by:

Leaderboards.save(PlayerScore score, LeaderboardSaveHandler callback);
PlayerScore score = new PlayerScore();
score.setTable("table");
score.setPlayerName("fred");
score.setPoints(20000);

Leaderboards.save (score, new LeaderboardSaveHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();

  }

  @Override
  public void onSuccess(PResponse response) {
  }
});

// a more advanced score
PlayerScore score2 = new PlayerScore();
score2.setTable("table");
score2.setPlayerName("fred");
score2.setPlayerId("fred@testuri.com");
score2.setPoints(20000);
score2.setField("custom", "field");
score2.setAllowDuplicates();

Leaderboards.save (score2, new LeaderboardSaveHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }

  @Override
  public void onSuccess(PResponse response) {
  }
});

Showing scores

Scores are loaded via a simple method that returns an array of scores to your function where you can display the data in your leaderboard.

To avoid try/catching everywhere there is a ListOptions helper class that

Leaderboards.list(JSONObject options, LeaderboardListHandler callback);

List options

Property Type Description
table String The name of the score table
highest Boolean The sort ordering by highest or lowest
allowduplicates Boolean Reject scores if they're not the player's best (default false) or allow multiple scores per player
filters JSONObject Additional properties to filter by from the 'save' fields
source String The website or device the score occurred on
friendslist JSONArray Array of friend's playerids
playerid String A specific playerid to filter by
excludeplayerid Boolean For excluding the playerid as a filter when you use saveAndList
mode String Time limits, 'last7days', 'last30days', 'alltime' (default), 'today' and 'newest' which returns latest unsorted scores.
Pagination
page int Page number to return (default is 1)
perpage int Results per page (default is 20)

For more concise code there is a helper object "ListOptions" that can be used instead of a JSONObject.

Method Description
set(String, Object) Sets a list option
setFieldFilter(String, Object) Sets a filter for custom fields
ListOptions options = new ListOptions();
options.set("table", "highscores");
options.set("highest", true);
options.set("perpage", 10);

Leaderboards.list (options, new LeaderboardListHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with r.getErrorCode();
  }

  @Override
  public void onSuccess(ArrayList<PlayerScore> scores, int numscores, PResponse response) {
    Log.d("Playtomic", "Got " + scores.size() + " scores out of " + numscores + " total");
    for(PlayerScore score : scores) {
      Log.d("Playtomic", score);
    }
  }
});

Save and list

You can submit scores and at the same time return the leaderboard page that that score is on. This combines the Save and List approaches from above:

Leaderboards.saveAndList(PlayerScore score, LeaderboardListHandler callback)

Note: If you pass a 'playerid' to be saved you can exclude it from filtering the returned scores via the additional option, excludeplayerid = true

You don't specify a 'page', you specify the 'perpage' (default 20) and it will automatically decide which page to return based on the submitted score's rank. If you submit the 1187th best score at 30 per page then it will show you page 39, scores #1170 - #1200.

Ranks are returned so you are not viewing the top N scores you are viewing the top N scores from rank X onwards.

Level sharing

The level sharing API provides a way to store and retrieve user-generated content for your game. It can operate anonymously or authenticated via any 3rd party service you're already using.

PlayerLevel structure

Saving and listing levels uses the PlayerLevel class which extrends JSONObject to represent a level.

Getter Setter Type Description
getName setName String The level name
getPlayerName setPlayerName String The player name
getPlayerId setPlayerId String Facebook or other userids, used for filtering by friends.
getData setData String The created level data as a string
getSource setSource String The website or device the score occurred on
getFields -- JSONObject Any additional data you want to (or have) attached to a level.
setField(String, Object) void Sets a custom field.

Saving levels

PlayerLevels.save(PlayerLevel level, PlayerLevelSaveLoadHandler callback);

Example saving level:

PlayerLevel level = new PlayerLevel();
level.setName("my level");
level.setPlayerName("ben");
level.setData("this is the level data");

PlayerLevels.save (level, new PlayerLevelSaveLoadHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }

  @Override
  public void onSuccess(PlayerLevel level, PResponse response) {
    Log.d("Playtomic", "Saved level id is " + level.getLevelId());
  }
});

Rating levels

Levels can be rated 1 - 10 by players. Rating can be done anonymously with some protection against repeat voting, or bound to playerids if you specify them.

PlayerLevels.rate(String levelid, int rating, PlayerLevelRateHandler callback);

Example rating level:

PlayerLevels.rate (level.getLevelId(), 7, new PlayerLevelRateHandler() {

  @Override
  public void onSuccess(PResponse response) {
    // Rating succeeded
  }

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }
});

Listing levels

Listing levels can be done by popular or newest, with optional filtering by date ranges and/or custom fields.

You can use either the helper class ListOptions or a JSONObject.

PlayerLevels.list(ListOptions options, PlayerLevelListHandler callback);

Listing options

Property Type Description
mode String
  • alltime
    The most popular levels based on all time ratings
  • newest
    The most recently created levels
  • recentaverage
    Average calculated across just the last 100 votes a level received
  • todayaverage | yesterdayaverage | last7daysaverage | last30daysaverage | last90daysaverage
    Aggregated rating averages on / in the specified timeframe
datemin String 'mm/dd/yyyy' for the minimum date the level was created.
datemax String 'mm/dd/yyyy' for the maximum date the level was created.
playerid String Facebook or other userid
friendslist JSONArray Array of friend's playerids
data Boolean Return the level data with the request (maybe faster to load individually)
source String The website or device the level was created on
filters JSONObject Any additional data you want to (or have) attached to a level.
Pagination
page int Page number to return (default is 1)
perpage int Results per page (default is 20)

An example listing levels:

ListOptions options = new ListOptions();
options.set("perpage", 30);
options.set("data", false);
options.set("mode", "newest");
options.setFieldFilter("difficulty", "hard");

PlayerLevels.list (options, new PlayerLevelListHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }

  @Override
  public void onSuccess(ArrayList<PlayerLevel> levels, int numlevels, PResponse response) {
    Log.d("Playtomic", "Got " + levels.size() + " levels out of " + numlevels + " total");
    for(PlayerLevel level : levels) {
      Log.d("Playtomic", level);
    }
  }
});

Loading levels

If you do not include the data when you load lists of levels then you can request it seperately.

PlayerLevels.load(String levelid, PlayerLevelSaveLoadHandler callback);

An example loading a single level:

PlayerLevels.load (levelid, new PlayerLevelSaveLoadHandler() {

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }

  @Override
  public void onSuccess(PlayerLevel level, PResponse response) {
    Log.d("Playtomic", "Got " + level);
  }
});

GameVars

GameVars let you change the value of key variables in your game any time you want.

Setting them up in your database

In your MongoHQ dashboard add a new entry to the "gamevars" collection.

{
  name: "basehitpoints",
  value: 800
}

Loading

They are loaded via:

GameVars.load(GameVarsHandler callback);

You can load variables individually, for instance if you are caching the GameVars you can check a 'version' GameVar to decide whether to reload the full collection.

GameVars.loadSingle("name", callback);

The callback parameter is your function that receives an object that has properties matching the variables you have configured in your database. The callback is the same for all or single GameVars.

// our variables with default, original values
int basehitpoints = 100;
int basegold = 50;

void initialiseGame()
{
  GameVars.load(new GameVarsHandler() {

    @Override
    public void onSuccess(Hashtable<String, Object> gv, PResponse response) {
      basehitpoints = (int)gv.get("basehitpoints");
      basegold = (int)gv.get("basegold");
    }

    @Override
    public void onFailure(PResponse response) {
      // request failed with response.getErrorCode();
    }
  });
}

Geolocation

The GeoIP service identifies which country the player is from, returning their country code and name.

It is called via:

GeoIP.lookup(GeoIPHandler callback);

The callback function receives a PlayerCountry that has 'code' and 'name' properties:

GeoIP.lookup(new GeoIPHandler() {

  @Override
  public void onSuccess(PlayerCountry country, PResponse response) {
    Log.d("Playtomic", "Player is from " + country.getCode() + " / " + country.getName());
  }

  @Override
  public void onFailure(PResponse response) {
    // request failed with response.getErrorCode();
  }
});