I foolishly thought simply changing my build.gradle file to use
implementation 'com.android.billingclient:billing:5.0.0'
instead of
implementation 'com.android.billingclient:billing:3.0.0'
Would solve all issues, and even though the project compiles, I can't be sure it works correctly.
my IAPServices.java is;
public class IAPServices {
public IabHelper mHelper;
public IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
public OnPurchaseRemoveAd mOnPurchaseRemoveAd;
Activity context;
public IAPServices(Activity context)
{
this.context = context;
}
public void loadAppPurchase() {
String base64EncodedPublicKey = AppicationContants.GooglePlayAppId;
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(
com.zeapps.util.IabResult result) {
// TODO Auto-generated method stub
if (!result.isSuccess()) {
Log.d("Purchase", "In-app Billing setup failed: " + result);
} else {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result,
com.zeapps.util.Inventory inventory) {
// TODO Auto-generated method stub
if (result.isFailure()) {
// handle error
// showToast("Fail Purchase");
return;
} else {
// showToast("Success Purchase");
Purchase removeadvertsPurchase = inventory
.getPurchase(AppicationContants.REMOVE_ADVERTS_ID);
AppicationContants.RemoveAdvertisements = (removeadvertsPurchase != null);
}
}
};
mHelper.queryInventoryAsync(mGotInventoryListener);
}
}
});
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
// TODO Auto-generated method stub
if (result.isFailure()) {
} else if (result.isSuccess()) {
String sku = purchase.getSku();
if (sku.equals(AppicationContants.REMOVE_ADVERTS_ID)) {
RaiseOnPurchaseRemoveAd();
AppicationContants.RemoveAdvertisements = true;
}
}
}
};
}
public void showInAppPurchase(String id) {
if (mHelper != null)
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(context, id, AppicationContants.IAP_REQUEST,
mPurchaseFinishedListener, "");
}
private void RaiseOnPurchaseRemoveAd() {
if (mOnPurchaseRemoveAd != null) {
mOnPurchaseRemoveAd.onEvent();
}
}
public interface OnPurchaseRemoveAd {
public void onEvent();
}
}
But I see so many 'cancelled' orders that have not even been purchased, so cannot help but think it is not correct, although no errors are showing.
Is the billing upgrade a bit more than just upgrading the gradle file??
Related
billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(#NonNull BillingResult billingResult, #Nullable List<Purchase> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null){
for(Purchase purchase: list) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
!purchase.isAcknowledged()) {
//test
try {
coinsHandler.addCoins(150, coinsTextView);
} catch (IOException e) {
System.err.println("Could not add coins from bonus !!!!");
}
verifyPurchase(purchase);
}
}
}
}
}).build();
connectToGooglePlayBilling();
I´m not sure where to put the added Coins, this place works fine, but i dont know how to implement more Items with different values.
private void connectToGooglePlayBilling(){
billingClient.startConnection(
new BillingClientStateListener() {
#Override
public void onBillingServiceDisconnected() {
connectToGooglePlayBilling();
}
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
getProductDetails();
}
}
}
);
}
private void verifyPurchase(Purchase purchase) {
String requestUrl = "https://xxxxxxx?" +
"purchaseToken=" + purchase.getPurchaseToken() + "&" +
"purchaseTime" + purchase.getPurchaseTime()+ "&" +
"orderId" + purchase.getOrderId();
Activity activity = this;
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
requestUrl,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject purchaseInfoFromServer = new JSONObject(response);
if(purchaseInfoFromServer.getBoolean("isValid")) {
ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchase.getPurchaseToken()).build();
billingClient.consumeAsync(
consumeParams,
new ConsumeResponseListener() {
#Override
public void onConsumeResponse(#NonNull BillingResult billingResult, #NonNull String s) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
Toast.makeText(activity, "Consumed!", Toast.LENGTH_LONG).show();
}
}
}
);
}
} catch (Exception err) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(this).add(stringRequest);
}
here some more code
private void getProductDetails(){
List<String> productIds = new ArrayList<>();
productIds.add("itemone");
//item2 test
productIds.add("itemtwo");
SkuDetailsParams getProductDetailsQuery = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
Activity activity = this;
billingClient.querySkuDetailsAsync(
getProductDetailsQuery,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
list != null){
TextView itemNameTextView = findViewById(R.id.itemName);
Button itemPriceButton = findViewById(R.id.itemPrice);
SkuDetails itemInfo = list.get(0);
//item2 test
TextView itemName2TextView = findViewById(R.id.itemName2);
Button itemPrice2Button = findViewById(R.id.itemPrice2);
SkuDetails itemInfo2 = list.get(1);
itemNameTextView.setText(itemInfo.getTitle());
itemPriceButton.setText(itemInfo.getPrice());
//item2 test
itemName2TextView.setText(itemInfo2.getTitle());
itemPrice2Button.setText(itemInfo2.getPrice());
itemPriceButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo).build()
);
}
}
);
//item2 test
itemPrice2Button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo2).build()
);
}
});
}
}
}
);
}
here i got the two different buy buttons working, with different prices and Ingame Items, but i dont know how to give the right item on the right button.
I am trying to make example of Play Billing application described here
In Last step they have described
To clean all the resources and unregister the observer, you just need to call BillingClient.endConnection. So define a method with this call inside BillingManager and then call it from GamePlayActivity.onDestroy:
according to above information I have made function called destroy like this in BillingManagerjava class.
public void destroy() {
mBillingClient.endConnection();
}
My Full BillingManager Class is like below
public class BillingManager implements PurchasesUpdatedListener {
private final BillingClient mBillingClient;
private final Activity mActivity;
private static final String TAG = "BillingManager";
public BillingManager(Activity activity) {
mActivity = activity;
mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponse) {
if (billingResponse == BillingClient.BillingResponse.OK) {
Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
} else {
Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
}
}
#Override
public void onBillingServiceDisconnected() {
Log.w(TAG, "onBillingServiceDisconnected()");
}
});
}
public void startPurchaseFlow(final String skuId, final String billingType) {
// Specify a runnable to start when connection to Billing client is established
Runnable executeOnConnectedService = new Runnable() {
#Override
public void run() {
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setType(billingType)
.setSku(skuId)
.build();
mBillingClient.launchBillingFlow(mActivity, billingFlowParams);
}
};
// If Billing client was disconnected, we retry 1 time
// and if success, execute the query
startServiceConnectionIfNeeded(executeOnConnectedService);
}
#Override
public void onPurchasesUpdated(#BillingClient.BillingResponse int responseCode,
List<Purchase> purchases) {
Log.d(TAG, "onPurchasesUpdated() response: " + responseCode);
}
private static final HashMap<String, List<String>> SKUS;
static
{
SKUS = new HashMap<>();
SKUS.put(BillingClient.SkuType.INAPP, Arrays.asList("gas", "premium"));
SKUS.put(BillingClient.SkuType.SUBS, Arrays.asList("gold_monthly", "gold_yearly"));
}
public List<String> getSkus(#BillingClient.SkuType String type) {
return SKUS.get(type);
}
public void querySkuDetailsAsync(#BillingClient.SkuType final String itemType,
final List<String> skuList, final SkuDetailsResponseListener listener) {
// Specify a runnable to start when connection to Billing client is established
Runnable executeOnConnectedService = new Runnable() {
#Override
public void run() {
SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder()
.setSkusList(skuList).setType(itemType).build();
mBillingClient.querySkuDetailsAsync(skuDetailsParams,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode,
List<SkuDetails> skuDetailsList) {
listener.onSkuDetailsResponse(responseCode, skuDetailsList);
}
});
}
};
// If Billing client was disconnected, we retry 1 time
// and if success, execute the query
startServiceConnectionIfNeeded(executeOnConnectedService);
}
private void startServiceConnectionIfNeeded(final Runnable executeOnSuccess) {
if (mBillingClient.isReady()) {
if (executeOnSuccess != null) {
executeOnSuccess.run();
}
} else {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponse) {
if (billingResponse == BillingClient.BillingResponse.OK) {
Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
if (executeOnSuccess != null) {
executeOnSuccess.run();
}
} else {
Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
}
}
#Override
public void onBillingServiceDisconnected() {
Log.w(TAG, "onBillingServiceDisconnected()");
}
});
}
}
public void destroy() {
mBillingClient.endConnection();
}
}
And My GamePlayActivity is like below
public class GamePlayActivity extends FragmentActivity implements BillingProvider {
#Override
protected void onDestroy() {
super.onDestroy();
// I want call method here
}
}
Now I want call above function in my game play activity. I have no idea how to call it.
As it mentioned in documentation
call it from GamePlayActivity.onDestroy
but you defined your own method.
Override onDestroy method of GamePlayActivity and put mBillingClient.endConnection(); into it.
#Override
protected void onDestroy() {
mBillingClient.endConnection();
}
I assume your Activity already has an instance of the BillingManager
public class GamePlayActivity extends FragmentActivity implements BillingProvider {
BillingManager bm; // assign this in onCreate
#Override
protected void onDestroy() {
super.onDestroy();
bm.destroy();
}
}
I have been following this tutorial I found on GitHub to try and make a connection to an OpenFire server. I have used spark before and am now trying to use Smack api to create a simple android app to use on the go. I have followed a few tutorials and eventually stumbled upon this from Github:
https://github.com/axcl/SMACK-API-Android-Demo
The problem is when I click the login button, I do not see my presence online in the OpenFire administrator panel.
Here is the code:
Myxmpp.java
public class Myxmpp {
private static final String DOMAIN = "192.168.2.14";
private static final String HOST = "192.168.2.14";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
//Initialize
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
}
ConnectXmpp.java
public class ConnectXmpp extends Service {
private String userName;
private String passWord;
private Myxmpp xmpp = new Myxmpp();
public ConnectXmpp() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new Localbinder<ConnectXmpp>(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if(intent != null){
userName = intent.getStringExtra("user");
passWord = intent.getStringExtra("pwd");
xmpp.init(userName, passWord);
xmpp.connectConnection();
}
return 0;
}
#Override
public void onDestroy() {
xmpp.disconnectConnection();
super.onDestroy();
}
Main Activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ConnectXmpp mService;
private View view;
private boolean mBounded;
private final ServiceConnection mConnection = new ServiceConnection() {
#SuppressWarnings("unchecked")
#Override
public void onServiceConnected(final ComponentName name,
final IBinder service) {
mService = ((Localbinder<ConnectXmpp>) service).getService();
mBounded = true;
Log.d(TAG, "onServiceConnected");
}
#Override
public void onServiceDisconnected(final ComponentName name) {
mService = null;
mBounded = false;
Log.d(TAG, "onServiceDisconnected");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Click Handler for Login Button
public void onClickLoginBtn(View view)
{
try {
EditText userId = (EditText) findViewById(R.id.username);
EditText userPwd = (EditText) findViewById(R.id.password);
String userName = userId.getText().toString();
String passWord = userPwd.getText().toString();
Intent intent = new Intent(getBaseContext(),ConnectXmpp.class );
intent.putExtra("user",userName);
intent.putExtra("pwd",passWord);
startService(intent);
//mService.connectConnection(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I know this is a lot but I am really confused with this whole XMPP stuff. Any help on how to connect an already registered user would be greatly appreciated. Thanks
hi i have checked your code and are you sure your domain name and host name is same. According to your issue, you are not able to login with xmpp using app.
Try this github example.This made my me.So if you got any issue i can help you.
https://github.com/saveendhiman/XMPPSample_Studio
Thank you hope this will help you.
Hello guys,
I have been trying to implement google play services with LibGDX and am trying to create a Quickgame() where everyone is auto matched. However, on the public void onRoomCreated(int arg0, Room arg1) method, the when i print out the status code, it keeps giving me 6.
I have tried several solutions but to no avail
Relinking the game and ensuring the SHA1 code is correct. (Sign in works correctly)
Checking my phones network status, it is connected to the internet.
Does anyone perhaps have a solution? Thank you!
public class GSGameHelper extends GameHelper implements RoomUpdateListener, RealTimeMessageReceivedListener,RoomStatusUpdateListener {
final static String TAG = "ButtonClicker2000";
static final int RC_SELECT_PLAYERS = 10000;
static final int RC_WAITING_ROOM = 10002;
private Activity activity;
private String mRoomID;
private MacroHardv2 game;
public GSGameHelper(Activity activity, int clientsToUse) {
super(activity, clientsToUse);
this.activity = activity;
// TODO Auto-generated constructor stub
}
public void quickGame(){
Bundle am = RoomConfig.createAutoMatchCriteria(1, 1, 0);
RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
roomConfigBuilder.setAutoMatchCriteria(am);
RoomConfig roomConfig = roomConfigBuilder.build();
Games.RealTimeMultiplayer.create(getApiClient(), roomConfig);
// prevent screen from sleeping during handshake
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public void initMatch(){
Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(getApiClient(), 1, 1);
this.activity.startActivityForResult(intent, RC_SELECT_PLAYERS);
}
private RoomConfig.Builder makeBasicRoomConfigBuilder() {
return RoomConfig.builder((RoomUpdateListener) this)
.setMessageReceivedListener((RealTimeMessageReceivedListener) this)
.setRoomStatusUpdateListener((RoomStatusUpdateListener) this);
}
public void onActivityResult(int request,int response, Intent data){
if (request == GSGameHelper.RC_WAITING_ROOM){
if (response == Activity.RESULT_CANCELED || response == GamesActivityResultCodes.RESULT_LEFT_ROOM ){
Games.RealTimeMultiplayer.leave(getApiClient(), this, mRoomID);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
BaseGameUtils.showAlert(activity, "Partida abandonada");
}else{
BaseGameUtils.showAlert(activity, "Comenzando partida");
this.game.multiplayerGameReady();
}
}
else if (request == GSGameHelper.RC_SELECT_PLAYERS){
if (response != Activity.RESULT_OK) {
// user canceled
return;
}
// get the invitee list
Bundle extras = data.getExtras();
final ArrayList<String> invitees =
data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
// get auto-match criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers =
data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers =
data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
Gdx.app.log("J", "Jmin" + minAutoMatchPlayers + " Jmax:" + maxAutoMatchPlayers);
for (String invitee : invitees){
Gdx.app.log("L" , invitee);
}
if (minAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
} else {
autoMatchCriteria = null;
}
// create the room and specify a variant if appropriate
RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
roomConfigBuilder.addPlayersToInvite(invitees);
if (autoMatchCriteria != null) {
roomConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
}
RoomConfig roomConfig = roomConfigBuilder.build();
Games.RealTimeMultiplayer.create(getApiClient(), roomConfig);
// prevent screen from sleeping during handshake
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
super.onActivityResult(request, response, data);
}
}
#Override
public void onJoinedRoom(int arg0, Room arg1) {
if (arg0 != GamesStatusCodes.STATUS_OK) {
Gdx.app.log("R", "Joined FAILED");
}else{
Gdx.app.log("R", "Joined Room");
}
}
#Override
public void onLeftRoom(int arg0, String arg1) {
BaseGameUtils.makeSimpleDialog(activity, "Abandonado partida");
Gdx.app.log("LEAVE", "Me fui de la Room");
}
#Override
public void onRoomConnected(int arg0, Room arg1) {
// TODO Auto-generated method stub
}
public void setGame(MacroHardv2 game){
this.game = game;
}
#Override
public void onRoomCreated(int arg0, Room arg1) {
if (arg0 != GamesStatusCodes.STATUS_OK) {
//BaseGameUtils.showAlert(activity, "Room creation error");
BaseGameUtils.makeSimpleDialog(activity, "Error al crear la partida", "Room creation error " + arg0).show();
Gdx.app.log("R", "Room Created FAILED");
}else{
Gdx.app.log("R", "Room Created");
mRoomID = arg1.getRoomId();
Intent i = Games.RealTimeMultiplayer.getWaitingRoomIntent(getApiClient(), arg1, 2);
this.activity.startActivityForResult(i, RC_WAITING_ROOM);
}
}
public void sendPos(float x,float y){
try{
byte[] mensaje;
mensaje = ByteBuffer.allocate(8).putFloat(x).putFloat(y).array();
Games.RealTimeMultiplayer.sendUnreliableMessageToOthers(getApiClient(), mensaje, mRoomID);
}catch(Exception e){
}
}
#Override
public void onRealTimeMessageReceived(RealTimeMessage rtm) {
float x, y;
byte[] b = rtm.getMessageData();
ByteBuffer bf = ByteBuffer.wrap(b);
x = bf.getFloat();
y = bf.getFloat();
game.updateGameWorld(x,y);
}
#Override
public void onConnectedToRoom(Room arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnectedFromRoom(Room arg0) {
// TODO Auto-generated method stub
}
#Override
public void onP2PConnected(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onP2PDisconnected(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPeerDeclined(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPeerInvitedToRoom(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPeerJoined(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPeerLeft(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPeersConnected(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPeersDisconnected(Room arg0, List<String> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onRoomAutoMatching(Room arg0) {
// TODO Auto-generated method stub
}
#Override
public void onRoomConnecting(Room arg0) {
// TODO Auto-generated method stub
}
}
Based on this documentation, you need to check if multiplayer support is enabled for your client ID. You need to enable real-time multiplayer support in the Developer Console. Check this link on how to enable multiplayer support.
This SO ticket might also help.
I'm trying to implment in app puchase/billing in my app so when the user buys the item i remove the ads. I have and example code that is working with SKU = "android.test.purchased". Now my question is how can I link the app to my items - I have uploaded new apk with billing enabled, created and published the item one hour ago, but when I try to buy the item I get this:
here is my code:
public class RemoveAds extends AthanBaseActivity implements OnClickListener {
private static final String TAG = "inappbilling";
IabHelper mHelper;
//ID from playstore 16xxxx15_removeads.
//android.test.purchased
static final String ITEM_SKU = "com.myapppackage.16xxxx15_removeads.";
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.remove_ads);
findViewById( R.id.remove_ads_).setOnClickListener(this);
setupInAppPurchase();
}
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
Toast.makeText(RemoveAds.this, "SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(RemoveAds.this, "ERROR purchase",
Toast.LENGTH_LONG).show();
// handle error
}
}
};
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
// buyButton.setEnabled(false);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void setupInAppPurchase() {
String base64EncodedPublicKey = "MIIBIjANBgkqhkcccxxxxxdomr somelongstringdfsdfsdfsfsdofksdofkdsMXz0R4EJuw7YZkQ8jMPemymSbQGtLllH+fu85hfQIDAQAB";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.remove_ads_:
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
break;
}
}
}
You cannot make purchases if the primary account on your real android device is same as your developer account.