I have been trying out Google Play Services Multiplayer APK, and have tried out the sample code, "Button Clicker" as shown below.
However, I am not sure how to port this over to LibGDX as currently the code is running based off a normal project without the "core" and "androidlauncher" that libGDX has. Does anyone perhaps have any advise on how should i do it? From what i know, core has a Mainclass with a method called render() which always run in a loop. However I cant think of a way of integrating it.
I have checked out several websites , However, could i ask why cant i just place the whole Buttonclicker project into the core module and call methods from it? Like sign in and sign out.
I only require the functionalities currently implemented in Button Clicker
CODE AS FOLLOWS:
/* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryanhello;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesStatusCodes;
import com.google.android.gms.games.GamesActivityResultCodes;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.Multiplayer;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Participant;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessageReceivedListener;
import com.google.android.gms.games.multiplayer.realtime.Room;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateListener;
import com.google.android.gms.games.multiplayer.realtime.RoomUpdateListener;
import com.google.android.gms.plus.Plus;
import com.google.example.games.basegameutils.BaseGameUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Button Clicker 2000. A minimalistic game showing the multiplayer features of
* the Google Play game services API. The objective of this game is clicking a
* button. Whoever clicks the button the most times within a 20 second interval
* wins. It's that simple. This game can be played with 2, 3 or 4 players. The
* code is organized in sections in order to make understanding as clear as
* possible. We start with the integration section where we show how the game
* is integrated with the Google Play game services API, then move on to
* game-specific UI and logic.
*
* INSTRUCTIONS: To run this sample, please set up
* a project in the Developer Console. Then, place your app ID on
* res/values/ids.xml. Also, change the package name to the package name you
* used to create the client ID in Developer Console. Make sure you sign the
* APK with the certificate whose fingerprint you entered in Developer Console
* when creating your Client Id.
*
* #author Bruno Oliveira (btco), 2013-04-26
*/
public class MainActivity extends Activity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener, RealTimeMessageReceivedListener,
RoomStatusUpdateListener, RoomUpdateListener, OnInvitationReceivedListener {
/*
* API INTEGRATION SECTION. This section contains the code that integrates
* the game with the Google Play game services API.
*/
final static String TAG = "ButtonClicker2000";
// Request codes for the UIs that we show with startActivityForResult:
final static int RC_SELECT_PLAYERS = 10000;
final static int RC_INVITATION_INBOX = 10001;
final static int RC_WAITING_ROOM = 10002;
// Request code used to invoke sign in user interactions.
private static final int RC_SIGN_IN = 9001;
// Client used to interact with Google APIs.
private GoogleApiClient mGoogleApiClient;
// Are we currently resolving a connection failure?
private boolean mResolvingConnectionFailure = false;
// Has the user clicked the sign-in button?
private boolean mSignInClicked = false;
// Set to true to automatically start the sign in flow when the Activity starts.
// Set to false to require the user to click the button in order to sign in.
private boolean mAutoStartSignInFlow = true;
// Room ID where the currently active game is taking place; null if we're
// not playing.
String mRoomId = null;
// Are we playing in multiplayer mode?
boolean mMultiplayer = false;
// The participants in the currently active game
ArrayList<Participant> mParticipants = null;
// My participant ID in the currently active game
String mMyId = null;
// If non-null, this is the id of the invitation we received via the
// invitation listener
String mIncomingInvitationId = null;
// Message buffer for sending messages
byte[] mMsgBuf = new byte[2];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the Google Api Client with access to Plus and Games
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
// set up a click listener for everything we care about
for (int id : CLICKABLES) {
findViewById(id).setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.button_single_player:
case R.id.button_single_player_2:
// play a single-player game
resetGameVars();
startGame(false);
break;
case R.id.button_sign_in:
// user wants to sign in
// Check to see the developer who's running this sample code read the instructions :-)
// NOTE: this check is here only because this is a sample! Don't include this
// check in your actual production app.
if (!BaseGameUtils.verifySampleSetup(this, R.string.app_id)) {
Log.w(TAG, "*** Warning: setup problems detected. Sign in may not work!");
}
// start the sign-in flow
Log.d(TAG, "Sign-in button clicked");
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.button_sign_out:
// user wants to sign out
// sign out.
Log.d(TAG, "Sign-out button clicked");
mSignInClicked = false;
Games.signOut(mGoogleApiClient);
mGoogleApiClient.disconnect();
switchToScreen(R.id.screen_sign_in);
break;
case R.id.button_invite_players:
// show list of invitable players
intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(mGoogleApiClient, 1, 3);
switchToScreen(R.id.screen_wait);
startActivityForResult(intent, RC_SELECT_PLAYERS);
break;
case R.id.button_see_invitations:
// show list of pending invitations
intent = Games.Invitations.getInvitationInboxIntent(mGoogleApiClient);
switchToScreen(R.id.screen_wait);
startActivityForResult(intent, RC_INVITATION_INBOX);
break;
case R.id.button_accept_popup_invitation:
// user wants to accept the invitation shown on the invitation popup
// (the one we got through the OnInvitationReceivedListener).
acceptInviteToRoom(mIncomingInvitationId);
mIncomingInvitationId = null;
break;
case R.id.button_quick_game:
// user wants to play against a random opponent right now
startQuickGame();
break;
case R.id.button_click_me:
// (gameplay) user clicked the "click me" button
scoreOnePoint();
break;
}
}
void startQuickGame() {
// quick-start a game with 1 randomly selected opponent
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
switchToScreen(R.id.screen_wait);
keepScreenOn();
resetGameVars();
Games.RealTimeMultiplayer.create(mGoogleApiClient, rtmConfigBuilder.build());
}
#Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
switch (requestCode) {
case RC_SELECT_PLAYERS:
// we got the result from the "select players" UI -- ready to create the room
handleSelectPlayersResult(responseCode, intent);
break;
case RC_INVITATION_INBOX:
// we got the result from the "select invitation" UI (invitation inbox). We're
// ready to accept the selected invitation:
handleInvitationInboxResult(responseCode, intent);
break;
case RC_WAITING_ROOM:
// we got the result from the "waiting room" UI.
if (responseCode == Activity.RESULT_OK) {
// ready to start playing
Log.d(TAG, "Starting game (waiting room returned OK).");
startGame(true);
} else if (responseCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
// player indicated that they want to leave the room
leaveRoom();
} else if (responseCode == Activity.RESULT_CANCELED) {
// Dialog was cancelled (user pressed back key, for instance). In our game,
// this means leaving the room too. In more elaborate games, this could mean
// something else (like minimizing the waiting room UI).
leaveRoom();
}
break;
case RC_SIGN_IN:
Log.d(TAG, "onActivityResult with requestCode == RC_SIGN_IN, responseCode="
+ responseCode + ", intent=" + intent);
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (responseCode == RESULT_OK) {
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this,requestCode,responseCode, R.string.signin_other_error);
}
break;
}
super.onActivityResult(requestCode, responseCode, intent);
}
// Handle the result of the "Select players UI" we launched when the user clicked the
// "Invite friends" button. We react by creating a room with those players.
private void handleSelectPlayersResult(int response, Intent data) {
if (response != Activity.RESULT_OK) {
Log.w(TAG, "*** select players UI cancelled, " + response);
switchToMainScreen();
return;
}
Log.d(TAG, "Select players UI succeeded.");
// get the invitee list
final ArrayList<String> invitees = data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
Log.d(TAG, "Invitee count: " + invitees.size());
// get the automatch criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0 || maxAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
Log.d(TAG, "Automatch criteria: " + autoMatchCriteria);
}
// create the room
Log.d(TAG, "Creating room...");
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.addPlayersToInvite(invitees);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
if (autoMatchCriteria != null) {
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
}
switchToScreen(R.id.screen_wait);
keepScreenOn();
resetGameVars();
Games.RealTimeMultiplayer.create(mGoogleApiClient, rtmConfigBuilder.build());
Log.d(TAG, "Room created, waiting for it to be ready...");
}
// Handle the result of the invitation inbox UI, where the player can pick an invitation
// to accept. We react by accepting the selected invitation, if any.
private void handleInvitationInboxResult(int response, Intent data) {
if (response != Activity.RESULT_OK) {
Log.w(TAG, "*** invitation inbox UI cancelled, " + response);
switchToMainScreen();
return;
}
Log.d(TAG, "Invitation inbox UI succeeded.");
Invitation inv = data.getExtras().getParcelable(Multiplayer.EXTRA_INVITATION);
// accept invitation
acceptInviteToRoom(inv.getInvitationId());
}
// Accept the given invitation.
void acceptInviteToRoom(String invId) {
// accept the invitation
Log.d(TAG, "Accepting invitation: " + invId);
RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(this);
roomConfigBuilder.setInvitationIdToAccept(invId)
.setMessageReceivedListener(this)
.setRoomStatusUpdateListener(this);
switchToScreen(R.id.screen_wait);
keepScreenOn();
resetGameVars();
Games.RealTimeMultiplayer.join(mGoogleApiClient, roomConfigBuilder.build());
}
// Activity is going to the background. We have to leave the current room.
#Override
public void onStop() {
Log.d(TAG, "**** got onStop");
// if we're in a room, leave it.
leaveRoom();
// stop trying to keep the screen on
stopKeepingScreenOn();
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
switchToScreen(R.id.screen_sign_in);
}
else {
switchToScreen(R.id.screen_wait);
}
super.onStop();
}
// Activity just got to the foreground. We switch to the wait screen because we will now
// go through the sign-in flow (remember that, yes, every time the Activity comes back to the
// foreground we go through the sign-in flow -- but if the user is already authenticated,
// this flow simply succeeds and is imperceptible).
#Override
public void onStart() {
switchToScreen(R.id.screen_wait);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Log.w(TAG,
"GameHelper: client was already connected on onStart()");
} else {
Log.d(TAG,"Connecting client.");
mGoogleApiClient.connect();
}
super.onStart();
}
// Handle back key to make sure we cleanly leave a game if we are in the middle of one
#Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_BACK && mCurScreen == R.id.screen_game) {
leaveRoom();
return true;
}
return super.onKeyDown(keyCode, e);
}
// Leave the room.
void leaveRoom() {
Log.d(TAG, "Leaving room.");
mSecondsLeft = 0;
stopKeepingScreenOn();
if (mRoomId != null) {
Games.RealTimeMultiplayer.leave(mGoogleApiClient, this, mRoomId);
mRoomId = null;
switchToScreen(R.id.screen_wait);
} else {
switchToMainScreen();
}
}
// Show the waiting room UI to track the progress of other players as they enter the
// room and get connected.
void showWaitingRoom(Room room) {
// minimum number of players required for our game
// For simplicity, we require everyone to join the game before we start it
// (this is signaled by Integer.MAX_VALUE).
final int MIN_PLAYERS = Integer.MAX_VALUE;
Intent i = Games.RealTimeMultiplayer.getWaitingRoomIntent(mGoogleApiClient, room, MIN_PLAYERS);
// show waiting room UI
startActivityForResult(i, RC_WAITING_ROOM);
}
// Called when we get an invitation to play a game. We react by showing that to the user.
#Override
public void onInvitationReceived(Invitation invitation) {
// We got an invitation to play a game! So, store it in
// mIncomingInvitationId
// and show the popup on the screen.
mIncomingInvitationId = invitation.getInvitationId();
((TextView) findViewById(R.id.incoming_invitation_text)).setText(
invitation.getInviter().getDisplayName() + " " +
getString(R.string.is_inviting_you));
switchToScreen(mCurScreen); // This will show the invitation popup
}
#Override
public void onInvitationRemoved(String invitationId) {
if (mIncomingInvitationId.equals(invitationId)&&mIncomingInvitationId!=null) {
mIncomingInvitationId = null;
switchToScreen(mCurScreen); // This will hide the invitation popup
}
}
/*
* CALLBACKS SECTION. This section shows how we implement the several games
* API callbacks.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected() called. Sign in successful!");
Log.d(TAG, "Sign-in succeeded.");
// register listener so we are notified if we receive an invitation to play
// while we are in the game
Games.Invitations.registerInvitationListener(mGoogleApiClient, this);
if (connectionHint != null) {
Log.d(TAG, "onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint
.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
Log.d(TAG,"onConnected: connection hint has a room invite!");
acceptInviteToRoom(inv.getInvitationId());
return;
}
}
switchToMainScreen();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended() called. Trying to reconnect.");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed() called, result: " + connectionResult);
if (mResolvingConnectionFailure) {
Log.d(TAG, "onConnectionFailed() ignoring connection failure; already resolving.");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = BaseGameUtils.resolveConnectionFailure(this, mGoogleApiClient,
connectionResult, RC_SIGN_IN, getString(R.string.signin_other_error));
}
switchToScreen(R.id.screen_sign_in);
}
// Called when we are connected to the room. We're not ready to play yet! (maybe not everybody
// is connected yet).
#Override
public void onConnectedToRoom(Room room) {
Log.d(TAG, "onConnectedToRoom.");
//get participants and my ID:
mParticipants = room.getParticipants();
mMyId = room.getParticipantId(Games.Players.getCurrentPlayerId(mGoogleApiClient));
// save room ID if its not initialized in onRoomCreated() so we can leave cleanly before the game starts.
if(mRoomId==null)
mRoomId = room.getRoomId();
// print out the list of participants (for debug purposes)
Log.d(TAG, "Room ID: " + mRoomId);
Log.d(TAG, "My ID " + mMyId);
Log.d(TAG, "<< CONNECTED TO ROOM>>");
}
// Called when we've successfully left the room (this happens a result of voluntarily leaving
// via a call to leaveRoom(). If we get disconnected, we get onDisconnectedFromRoom()).
#Override
public void onLeftRoom(int statusCode, String roomId) {
// we have left the room; return to main screen.
Log.d(TAG, "onLeftRoom, code " + statusCode);
switchToMainScreen();
}
// Called when we get disconnected from the room. We return to the main screen.
#Override
public void onDisconnectedFromRoom(Room room) {
mRoomId = null;
showGameError();
}
// Show error message about game being cancelled and return to main screen.
void showGameError() {
BaseGameUtils.makeSimpleDialog(this, getString(R.string.game_problem));
switchToMainScreen();
}
// Called when room has been created
#Override
public void onRoomCreated(int statusCode, Room room) {
Log.d(TAG, "onRoomCreated(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomCreated, status " + statusCode);
showGameError();
return;
}
// save room ID so we can leave cleanly before the game starts.
mRoomId = room.getRoomId();
// show the waiting room UI
showWaitingRoom(room);
}
// Called when room is fully connected.
#Override
public void onRoomConnected(int statusCode, Room room) {
Log.d(TAG, "onRoomConnected(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomConnected, status " + statusCode);
showGameError();
return;
}
updateRoom(room);
}
#Override
public void onJoinedRoom(int statusCode, Room room) {
Log.d(TAG, "onJoinedRoom(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomConnected, status " + statusCode);
showGameError();
return;
}
// show the waiting room UI
showWaitingRoom(room);
}
// We treat most of the room update callbacks in the same way: we update our list of
// participants and update the display. In a real game we would also have to check if that
// change requires some action like removing the corresponding player avatar from the screen,
// etc.
#Override
public void onPeerDeclined(Room room, List<String> arg1) {
updateRoom(room);
}
#Override
public void onPeerInvitedToRoom(Room room, List<String> arg1) {
updateRoom(room);
}
#Override
public void onP2PDisconnected(String participant) {
}
#Override
public void onP2PConnected(String participant) {
}
#Override
public void onPeerJoined(Room room, List<String> arg1) {
updateRoom(room);
}
#Override
public void onPeerLeft(Room room, List<String> peersWhoLeft) {
updateRoom(room);
}
#Override
public void onRoomAutoMatching(Room room) {
updateRoom(room);
}
#Override
public void onRoomConnecting(Room room) {
updateRoom(room);
}
#Override
public void onPeersConnected(Room room, List<String> peers) {
updateRoom(room);
}
#Override
public void onPeersDisconnected(Room room, List<String> peers) {
updateRoom(room);
}
void updateRoom(Room room) {
if (room != null) {
mParticipants = room.getParticipants();
}
if (mParticipants != null) {
updatePeerScoresDisplay();
}
}
My current interface code
package com.macrohard.game;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.example.games.basegameutils.GameHelper;
import com.macrohard.game.SomeGame;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
import com.google.example.games.basegameutils.GameHelper.GameHelperListener;
import com.macrohard.game.ActionResolver;
import com.macrohard.game.MainMenu;
public class AndroidLauncher extends AndroidApplication implements ActionResolver {
private GameHelper gameHelper;
private final static int requestCode = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
gameHelper.enableDebugLog(false);
GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener()
{
#Override
public void onSignInFailed(){ }
#Override
public void onSignInSucceeded(){ }
};
gameHelper.setup(gameHelperListener);
//initialize(new SomeGame(), config);
initialize(new MainMenu(this), config);
}
//...
#Override
protected void onStart()
{
super.onStart();
gameHelper.onStart(this);
}
#Override
protected void onStop()
{
super.onStop();
gameHelper.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
gameHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void signIn()
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
gameHelper.beginUserInitiatedSignIn();
}
});
}
catch (Exception e)
{
Gdx.app.log("MainActivity", "Log in failed: " + e.getMessage() + ".");
}
}
#Override
public void signOut()
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
gameHelper.signOut();
}
});
}
catch (Exception e)
{
Gdx.app.log("MainActivity", "Log out failed: " + e.getMessage() + ".");
}
}
#Override
public void rateGame()
{
String str = "Your PlayStore Link";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));
}
#Override
public void unlockAchievement()
{
}
#Override
public void submitScore(int highScore)
{
}
#Override
public void showAchievement()
{
}
#Override
public void showScore()
{
}
#Override
public boolean isSignedIn()
{
return gameHelper.isSignedIn();
}
}
LibGDX separates platform specific codes into different modules for providing multiplatform by using the same code base (Core project). So you should implement android specific stuff in android project as you show in the code example.
You can not use any class in the package "com.google.android" in your core project. Because Google Play Services depends on android specific resources. You should read the document about platform specific code
https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
So, you should prepare an interface which defines your methods you want to use and implement separately for each of platforms that you are planning to support in your project.
It seems that we are both trying to implement a real-time multiplayer using the Google Play Games Services with the very specific architecture of any libGDX project. I suggest you to check out this GitHub repository : GarrapuchoFootball. Tell me if it helps you.
Related
I am working on an app that can connect to an adafruit flora BLE device to receive information from it. I want the app to display the list of found devices and when an item in the list view is clicked the connection is made and data can be received. Ultimately I want to take said data over to another activity to graph in realtime (if possible). There are a few things going on that i dont understand and I hope someone can shed light on.
When it is scanning for devices the list view shows them but there are multiples of each.
For some reason the onPause and onResume make the list view glitchy (displays devices and then removes them)
How do I know when there is a connection?
When I have getRemoteDevice in my code I get a runtime error ( Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on a null object reference)
When I try and use filters and settings in the startScan method I get nothing in my list, I have also tried null filters w/ settings and still nothing.
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.Intent;
import android.os.Build;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanFilter;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import no.nordicsemi.android.support.v18.scanner.ScanSettings;
public class BluetoothDiscovery extends AppCompatActivity {
private String TAG = "Bluetooth Device";
private int REQUEST_ENABLE_BT = 5;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScannerCompat scanner;
private ScanSettings settings;
private UUID baseUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // service UUID
private UUID txUUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // TX UUID characteristic
private UUID rxUUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // RX UUID characteristic
private ScanFilter scanFilter;
private BluetoothDevice device, mdevice;
private BluetoothGatt mGatt;
private boolean mScanning = false;
private ArrayList<deviceShowFormat> foundDevices = new ArrayList<>();
formattingAdapter BTadapter;
Button scanButton;
TextView fancyWords;
ListView deviceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_discovery);
mBluetoothAdapter.getDefaultAdapter();
scanButton = findViewById(R.id.scanButt);
scanButton.setText(getString(R.string.notScanning));
fancyWords = findViewById(R.id.discoverText);
fancyWords.setText(getString(R.string.nonScanTitle));
deviceList = findViewById(R.id.deviceList);
BTadapter = new formattingAdapter(BluetoothDiscovery.this, foundDevices);
deviceList.setAdapter(BTadapter);
scanner = BluetoothLeScannerCompat.getScanner();
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).setReportDelay(500).build();
scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(baseUUID)).build();
//scanner.startScan(Arrays.asList(scanFilter), settings, mScanCallback);
deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressLint("LongLogTag")
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
deviceShowFormat mBTDevice = foundDevices.get(i);
BluetoothDevice Device = mBTDevice.get_device();
String deviceName = mBTDevice.get_device_name();
String deviceAddress = mBTDevice.get_device_address();
Log.d(TAG, "Selected device: " + Device.toString());
Log.d(TAG, "Selected device name: " + deviceName);
Log.d(TAG, "Selected device address: " + deviceAddress);
//BluetoothDevice deviceConnect = mBluetoothAdapter.getRemoteDevice(deviceAddress);
//deviceConnect.createBond();
mGatt = Device.connectGatt(BluetoothDiscovery.this, false, mGattCallback);
Toast.makeText(BluetoothDiscovery.this, "Selected device: " + deviceName, Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Device.createBond();
}
Log.d(TAG, "" + Device.getBondState());
if(Device.getBondState() == BluetoothDevice.BOND_BONDED){
Toast.makeText(BluetoothDiscovery.this, "Bluetooth device connected successfully", Toast.LENGTH_SHORT).show();
}
mGatt.getServices();
mGatt.getConnectedDevices();
Log.d("THIS IS THE DEVICES UUID", String.valueOf(Device.getUuids()));
Log.d("DEVICE SERVICES", String.valueOf(mGatt.getServices()));
}
});
}
private final no.nordicsemi.android.support.v18.scanner.ScanCallback mScanCallback = new no.nordicsemi.android.support.v18.scanner.ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.i("onScanResult", "device detected");
device = result.getDevice();
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Log.d(TAG, "Scanned device: " + device.toString());
Log.d(TAG, "Scanned device name: " + deviceName);
Log.d(TAG, "Scanned device address: " + deviceAddress);
foundDevices.add(new deviceShowFormat(device, deviceName, deviceAddress));
BTadapter.notifyDataSetChanged();
}
};
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED){
Toast.makeText(BluetoothDiscovery.this, "Attempting service discovery", Toast.LENGTH_SHORT).show();
Log.i("onConnectionStateChange", "Attempting service discovery: " + gatt.discoverServices());
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED){
Toast.makeText(BluetoothDiscovery.this, "Connection has been terminated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status){
super.onServicesDiscovered(gatt, status);
Log.i("onServicesDiscovered", "Hey, we found a service");
if (status != BluetoothGatt.GATT_SUCCESS){
// Handle error
Log.d("onServicesDiscovered" , "" + status);
return;
}
BluetoothGattCharacteristic characteristic = gatt.getService(baseUUID).getCharacteristic(rxUUID);
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(txUUID);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
Log.i("onCharacteristicRead", "Characteristic has been read");
readCounterCharacteristic(characteristic);
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
if (mGatt.writeCharacteristic(characteristic)){
Log.d("Characteristic changed", "Possibly looking for a write");
}
if (mGatt.readCharacteristic(characteristic)){
readCounterCharacteristic(characteristic);
}
}
private void readCounterCharacteristic(BluetoothGattCharacteristic characteristic){
if (mGatt.readCharacteristic(characteristic)){
byte[] data = characteristic.getValue();
Log.d("READ DATA", data.toString());
}
// if (rxUUID.equals(characteristic.getUuid())){
// //byte[] data = characteristic.getValue();
// byte[] data = mGatt.readCharacteristic(characteristic);
// //int value = Ints.fromByteArray(data);
// Log.d("READ DATA", data.toString());
// }
}
};
public void toggleScan(View view){
mScanning = !mScanning;
if(mScanning){
scanner.startScan(mScanCallback); //Arrays.asList(scanFilter) null, settings,
scanButton.setText(getString(R.string.scanInProgress));
fancyWords.setText(getString(R.string.ScanTitle));
} else {
scanner.stopScan(mScanCallback);
scanButton.setText(getString(R.string.notScanning));
}
}
// #Override
// public void onPause(){
// super.onPause();
//
//// if(mScanning){
//// mScanning = !mScanning;
// scanner.stopScan(mScanCallback);
//// }
//
// //Empty Adapter
// //BTadapter.clear();
// //BTadapter.notifyDataSetChanged();
//
// //mdevice = device;
//
// }
//
// #Override
// public void onResume(){
// super.onResume();
//
// if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// }
//
// //device = mdevice;
// }
}
The code is the second activity in my app, in the first bluetooth is initialized and what-not. The above code works but I dont receive any data from the device and am not sure its truly connected. from the logs shown in the code I get:
Logcat
Logcat2
Resources im using:
https://github.com/NordicSemiconductor/Android-Scanner-Compat-Library
https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/uart-service
http://nilhcem.com/android-things/bluetooth-low-energy
You missed to initialize mBluetoothAdapter
As of (at oncreate):
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = manager.getAdapter();
instead of:
mBluetoothAdapter.getDefaultAdapter();
After that your variable is initialized and ready to use, just check if you need RuntimePermissions for using bluetooth.
Much of the stuff in android BLE communication is asynchronous.
So when you call Device.connectGatt(), you need to wait for the onConnectionStateChange callback before doing the next thing. Your attempts to enumerate the services will fail (probably quietly) because your connection state hasn't gone from 0 to 2 at that point. In your log you can see that you do the getServices() call before it has called you back to say the connection state has gone to connected.
Making things trickier, in my experience you should only be doing your BluetoothDevice interaction from the main thread. (Edit: Only sending requests from the main thread is apparently not a requirement)
So each command you do (connecting, reading characteristic values, writing, disconnecting, enumerating services, etc) needs to look like:
Main Thread: Call the (connect|read|write|enumerate) function
Callback thread: Java calls your BluetoothGattCallback, and you should find a way (Handler?) to signal the main thread to do your next thing.
Main thread: process the result from BluetoothGattCallback and trigger the next thing you'll be doing.
Mild aside: This is a lot easier in objective-c and react-native-ble-plx, because they handle the threading for you. If you design a good way to get the results from the callback thread to the main thread from the beginning, you will save yourself a lot of pain.
Example code for getting stuff back to the UI thread:
Handler m_handler;
public void onResume() {
m_handler = new Handler(); // creates a Handler bound to the UI thread, which lets us fire messages back and forth between threads.
}
// ... other stuff ...
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED){
// oh boy, we're connected. Let's try to discover services!
// m_handler.post() is a good way to make sure the thing you pass runs on the UI thread.
m_handler.post(new Runnable() {
#Override
public void run() {
gatt.discoverServices();
}
})
}
}
For anyone looking this up in the future: If you receive a message similar to D/BluetoothGatt: onConnectionUpdated() - Device=xx:xx:xx:xx:xx:xx interval=6 latency=0 timeout=500 status=0 you are connecting to the device but not "enough" to recieve info. For me it turned out i had to click the device to connect to a second time to actually recieve the data. I dont know why yet
in your answer
For anyone looking this up in the future: If you receive a message
similar to D/BluetoothGatt: onConnectionUpdated() -
Device=xx:xx:xx:xx:xx:xx interval=6 latency=0 timeout=500 status=0 you
are connecting to the device but not "enough" to recieve info. For me
it turned out i had to click the device to connect to a second time to
actually recieve the data. I dont know why yet
I Unfortunately got this problem, you can see in my question
BLE onDescriptorWrite is not trigger when writeDescriptor receive true
And What do you say is the second click device, your app or other ble device.
Thanks a lot.
I'm trying to manage in-app billing in my app and i used to succeed and get the in-app tester payment window but after a while im always getting this type of resultcode from the purchase which is :
BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED 7 - Failure to purchase since item is already owned
is there any way to prevent from this to happen?
Purchase purchasePremium = null;
// The helper object
IabHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
{
// Create the helper, passing it our context and the public key to verify signatures with
Log.d(TAG, "Creating IAB helper.");
mHelper = new IabHelper(this, base64EncodedPublicKey);
}
public void onConsumePremiumButtonClicked(View arg0) {
if(purchasePremium != null)
{
Log.d(TAG, "We have Premium. Consuming it.");
try {
mHelper.consumeAsync(purchasePremium, mConsumeFinishedListener);
} catch (IabHelper.IabAsyncInProgressException e) {
complain("Error consuming Premium. Another async operation in progress.");
writeToLogFile("\nError consuming Premium. Another async operation in progress.");
}
}
else
{
alert("Please Subscribe the Product before Consuming it.",TAG,ActivityPurchaseManagedProduct.this);
}
}
// Called when consumption is complete
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result);
// if we were disposed of in the meantime, quit.
if (mHelper == null) return;
if (result.isSuccess()) {
// successfully consumed, so we apply the effects of the item in our
// game world's logic, which in our case means filling the Premium tank a bit
alert(" Consume Premium Success full",TAG,ActivityPurchaseManagedProduct.this);;
purchasePremium = null;
}
else {
complain("Error while consuming: " + result);
}
Log.d(TAG, "End consumption flow.");
}
};
I want to play my Vimeo videos and I've followed the steps in https://github.com/vimeo/vimeo-networking-java.
I used this method to get the Video object and then load it into a WebView.
VimeoClient.getInstance().fetchNetworkContent(String uri, ModelCallback callback)
However, when I logged the result, it seems to indicate that it fails.
Here are my 2 Java files.
MyVimeoApplication.java
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import com.vimeo.networking.Configuration;
import com.vimeo.networking.Vimeo;
import com.vimeo.networking.VimeoClient;
public class MyVimeoApplication extends Application
{
private static final String SCOPE = "private public interact";
private static final boolean IS_DEBUG_BUILD = false;
// Switch to true to see how access token auth works.
private static final boolean ACCESS_TOKEN_PROVIDED = false;
private static Context mContext;
#Override
public void onCreate()
{
super.onCreate();
mContext = this;
Configuration.Builder configBuilder;
// This check is just as for the example. In practice, you'd use one technique or the other.
if (ACCESS_TOKEN_PROVIDED)
{
configBuilder = getAccessTokenBuilder();
Log.d("ACCESS_TOKEN", "PROVIDED");
}
else
{
configBuilder = getClientIdAndClientSecretBuilder();
Log.d("ACCESS_TOKEN", "NOT PROVIDED");
}
if (IS_DEBUG_BUILD) {
// Disable cert pinning if debugging (so we can intercept packets)
configBuilder.enableCertPinning(false);
configBuilder.setLogLevel(Vimeo.LogLevel.VERBOSE);
}
VimeoClient.initialize(configBuilder.build());
}
public Configuration.Builder getAccessTokenBuilder() {
// The values file is left out of git, so you'll have to provide your own access token
String accessToken = getString(R.string.access_token);
return new Configuration.Builder(accessToken);
}
public Configuration.Builder getClientIdAndClientSecretBuilder() {
// The values file is left out of git, so you'll have to provide your own id and secret
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
String codeGrantRedirectUri = getString(R.string.deeplink_redirect_scheme) + "://" +
getString(R.string.deeplink_redirect_host);
Configuration.Builder configBuilder =
new Configuration.Builder(clientId, clientSecret, SCOPE, null,
null);
// configBuilder.setCacheDirectory(this.getCacheDir())
// .setUserAgentString(getUserAgentString(this)).setDebugLogger(new NetworkingLogger())
// // Used for oauth flow
// .setCodeGrantRedirectUri(codeGrantRedirectUri);
return configBuilder;
}
public static Context getAppContext() {
return mContext;
}
public static String getUserAgentString(Context context) {
String packageName = context.getPackageName();
String version = "unknown";
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(packageName, 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
System.out.println("Unable to get packageInfo: " + e.getMessage());
}
String deviceManufacturer = Build.MANUFACTURER;
String deviceModel = Build.MODEL;
String deviceBrand = Build.BRAND;
String versionString = Build.VERSION.RELEASE;
String versionSDKString = String.valueOf(Build.VERSION.SDK_INT);
return packageName + " (" + deviceManufacturer + ", " + deviceModel + ", " + deviceBrand +
", " + "Android " + versionString + "/" + versionSDKString + " Version " + version +
")";
}
}
MainActivity.java
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
import com.vimeo.networking.VimeoClient;
import com.vimeo.networking.callbacks.AuthCallback;
import com.vimeo.networking.callbacks.ModelCallback;
import com.vimeo.networking.model.Video;
import com.vimeo.networking.model.error.VimeoError;
public class MainActivity extends AppCompatActivity
{
private VimeoClient mApiClient = VimeoClient.getInstance();
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("All of your API are belong to us...");
// ---- Client Credentials Auth ----
if (mApiClient.getVimeoAccount().getAccessToken() == null) {
// If there is no access token, fetch one on first app open
authenticateWithClientCredentials();
}
}
// You can't make any requests to the api without an access token. This will get you a basic
// "Client Credentials" gran which will allow you to make requests
private void authenticateWithClientCredentials() {
mProgressDialog.show();
mApiClient.authorizeWithClientCredentialsGrant(new AuthCallback() {
#Override
public void success()
{
Toast.makeText(MainActivity.this, "Client Credentials Authorization Success", Toast.LENGTH_SHORT).show();
mProgressDialog.hide();
mApiClient.fetchNetworkContent("https://vimeo.com/179708540", new ModelCallback<Video>(Video.class)
{
#Override
public void success(Video video)
{
// use the video
Log.d("VIDEO", "SUCCESS");
String html = video.embed != null ? video.embed.html : null;
if(html != null)
{
// html is in the form "<iframe .... ></iframe>"
// load the html, for instance, if using a WebView on Android, you can perform the following:
WebView webview = (WebView) findViewById(R.id.webView); // obtain a handle to your webview
webview.loadData(html, "text/html", "utf-8");
}
}
#Override
public void failure(VimeoError error)
{
Log.d("VIDEO", "FAIL");
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
// voice the error
}
});
}
#Override
public void failure(VimeoError error) {
Toast.makeText(MainActivity.this, "Client Credentials Authorization Failure", Toast.LENGTH_SHORT).show();
mProgressDialog.hide();
}
});
}
}
You can achive this by using external library VimeoExtractor. (my example in kotlin)
https://github.com/ed-george/AndroidVimeoExtractor
1. Step one.
Add lib to gradle.
2. Step Two - get stream url
private fun initializePlayer() {
progressBar.visible() //optional show user that video is loading.
VimeoExtractor.getInstance().fetchVideoWithURL(VIMEO_VIDEO_URL, null, object : OnVimeoExtractionListener {
override fun onSuccess(video: VimeoVideo) {
val videoStream = video.streams["720p"] //get 720p or whatever
videoStream?.let{
playVideo(videoStream)
}
}
override fun onFailure(throwable: Throwable) {
Timber.e("Error durning video stream fetch")
}
})
}
3. Step three - play when ready
fun playVideo(videoStream: String) {
runOnUiThread {
progressBar.gone() //hide progressBar
videoView.setBackgroundResource(R.drawable.splash_backgorund)
videoView.setVideoPath(videoStream)
videoView.requestFocus()
videoView.setOnPreparedListener { mp ->
mp.isLooping = true
videoView.start()
}
}
}
Java Version: I used "Jack the Ripper" answer with little changes:
Step 1:
Used below link to extract video path
https://github.com/ed-george/AndroidVimeoExtractor
Step 2: get Vimeo video path
private void initializePlayer() {
if(getIntent().getStringExtra("vimeo_vid_id")!=null){
vid_id = getIntent().getStringExtra("vimeo_vid_id");
}
VimeoExtractor.getInstance().fetchVideoWithIdentifier(vid_id, null, new OnVimeoExtractionListener() {
#Override
public void onSuccess(VimeoVideo video) {
String hdStream = video.getStreams().get("720p");
System.out.println("VIMEO VIDEO STREAM" + hdStream);
if (hdStream != null) {
playVideo(hdStream);
}
}
#Override
public void onFailure(Throwable throwable) {
}
});
}
Step 3: Play video in VideoView
private void playVideo(final String stream) {
runOnUiThread(new Runnable() {
#Override
public void run() {
final VideoView videoView = findViewById(R.id.vimeo_vv);
final MediaController mediacontroller = new MediaController(VimeoVideoActivity.this);
mediacontroller.setAnchorView(videoView);
videoView.setMediaController(mediacontroller);
videoView.setBackgroundColor(Color.TRANSPARENT);
Uri video = Uri.parse(stream);
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videoView.requestFocus();
videoView.start();
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
System.out.println("Video Finish");
finish();
}
});
}
});
}
The problem is that you are trying to use a url and the vimeo-networking library is expecting a uri.
The url you have is https://vimeo.com/179708540 - this is a web url to see a video on the Vimeo site. To use the vimeo-networking library you must provide a uri to the method you are using (in this case fetchNetworkContent); for the video in this question the uri would look like /videos/179708540. The vimeo-networking library will then use this uri to construct a url for connection with the Vimeo API - it will end up looking like https://api.vimeo.com/videos/179708540.
You don't need any library to get vimeo video url
You need to follow just these two steps
Call this url with vimeo video ID to get the JSON Response.
Parse the JSON Response
JSONArray streamArray = new JSONObject(<JSON Response String>)
.getJSONObject("request")
.getJSONObject("files")
.getJSONArray("progressive");
//Get info for each stream available
for (int streamIndex = 0; streamIndex < streamArray.length(); streamIndex++)
{
JSONObject stream = streamArray.getJSONObject(streamIndex);
String url = stream.getString("url");
String quality = stream.getString("quality");
}
I solved the issue by authenticating with simpler authentication
You can authenticate as per your choice for playing the link you can use my method in the link below by
I used Vimeo networking library which is the official library of vimeo
Here is the link to my answer
I able to configure what URI should I use
How to play the video by Video View or Exo Player
So, your solution is you can replace the code of native playback to embed code.
The code for embed is here
https://github.com/vimeo/vimeo-networking-java/tree/master#embed
Now replace the Native play code in my solution below to the embed code
Android Play Vimeo Video // this is the solution
Currently making an Android app and decided to integrate Paypal payment in it, so that the user is redirected to Paypal payment inside the app.
I found the Paypal SampleApp for what I want to do:
https://github.com/paypal/PayPal-Android-SDK.
Firstly, I tested it and it worked without errors with CONFIG_ENVIRONMENT set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK, and with the default sandbox sample acc (usr: sample#buy.com, pass:123123123).
Then I made an account on developer.paypal.com in order to make the payment to my Paypal account (with CONFIG_ENVIRONMENT set to PayPalConfiguration.ENVIRONMENT_PRODUCTION). I created an app and used the provided Client ID from the developer portal in the SampleApp. By doing that, the payment isn't completed, and gives the error:
request failure with http statusCode:400,exception:Bad Request
request failed with server response:{"name":"DUPLICATE_REQUEST_ID","debug_id":"9f83f9a8ce3e5","message":"The value of PayPal-Request-Id header has already been used","information_link":"https://developer.paypal.com/webapps/developer/docs/api/","details":[]}
DUPLICATE_REQUEST_ID
Note: I'm only using the "BUY A THING" option in the Sample App; not interested in the other options
The code of the class that handles the payment process:
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalOAuthScopes;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalProfileSharingActivity;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.paypal.android.sdk.payments.ShippingAddress;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class PaymentActivity extends Activity{
private static final String TAG = "PAYMENT";
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
private static final String CONFIG_CLIENT_ID = "i changed this field with my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static final int REQUEST_CODE_PROFILE_SHARING = 3;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(PaymentActivity.this, com.paypal.android.sdk.payments.PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(com.paypal.android.sdk.payments.PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getThingToBuy(String paymentIntent) {
return new PayPalPayment(new BigDecimal("1.0"), "USD", "DRINK",
paymentIntent);
}
/*
* This method shows use of optional payment details and item list.
*/
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(PaymentActivity.this, PayPalFuturePaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
public void onProfileSharingPressed(View pressed) {
Intent intent = new Intent(PaymentActivity.this, PayPalProfileSharingActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES, getOauthScopes());
startActivityForResult(intent, REQUEST_CODE_PROFILE_SHARING);
}
private PayPalOAuthScopes getOauthScopes() {
Set<String> scopes = new HashSet<String>(
Arrays.asList(PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL, PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS) );
return new PayPalOAuthScopes(scopes);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm =
data.getParcelableExtra(com.paypal.android.sdk.payments.PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
Toast.makeText(
getApplicationContext(),
"PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
} else if (resultCode == com.paypal.android.sdk.payments.PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth =
data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(
getApplicationContext(),
"Future Payment code received from PayPal", Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
"FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth =
data.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("ProfileSharingExample", auth.toJSONObject().toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("ProfileSharingExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(
getApplicationContext(),
"Profile Sharing code received from PayPal", Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
Log.e("ProfileSharingExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("ProfileSharingExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
"ProfileSharingExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
/**
* TODO: Send the authorization response to your server, where it can
* exchange the authorization code for OAuth access and refresh tokens.
*
* Your server must then store these tokens, so that your server code
* can execute payments for this user in the future.
*
* A more complete example that includes the required app-server to
* PayPal-server integration is available from
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
Thank you!
Turns out that the error occurs because the PayPal app is also installed on my phone. If I uninstall it, the payment is successfully done in the PRODUCTION environment.
PayPal will soon release a version of their app that patches this bug:
https://github.com/paypal/PayPal-Android-SDK/issues/272.
Developing a Project Tango Android app in the Java API, and I can't get the tablet to trigger an onXYZijAvailable callback, and I'd really like to use the depth data in my application.
Here is my code for setting up the Tango and attaching its listeners:
Upon Tango initialization:
try {
Log.d(TAG, "Creating TangoPoseHandler Object");
this.main = main;
mTango = new Tango(main);
mConfig = new TangoConfig();
mConfig = mTango.getConfig(TangoConfig.CONFIG_TYPE_CURRENT);
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_MOTIONTRACKING, true);
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_AUTORECOVERY, true);
framePairs = new ArrayList<TangoCoordinateFramePair>();
} catch (TangoErrorException e) {
Log.d("TANGO ERROR", "TangoErrorException");
}
During the activity's onResume():
if (!isTangoConnected) {
main.startActivityForResult(
Tango.getRequestPermissionIntent(Tango.PERMISSIONTYPE_MOTION_TRACKING),
Tango.TANGO_INTENT_ACTIVITYCODE);
}
Upon Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(MAIN_ACTIVITY, "Activity Result Triggered");
if (Tango.TANGO_INTENT_ACTIVITYCODE == requestCode) {
((TangoPoseHandler)poseHandler).setup(requestCode, resultCode, data);
}
}
The setup method called:
public void setup(int requestCode, int resultCode, Intent data) {
if (requestCode == Tango.TANGO_INTENT_ACTIVITYCODE) {
// Make sure the request was successful
if (resultCode == android.app.Activity.RESULT_CANCELED) {
Toast.makeText(main,
"This app requires Motion Tracking permission!",
Toast.LENGTH_LONG).show();
main.finish();
return;
}
try {
setTangoListeners();
} catch (TangoErrorException e) {
Log.d(TAG, "TANGO ERROR WHEN SETTING LISTENERS");
Toast.makeText(main, "Tango Error! Restart the app!",
Toast.LENGTH_SHORT).show();
return;
}
try {
mTango.connect(mConfig);
isTangoConnected = true;
} catch (TangoOutOfDateException e) {
Toast.makeText(main.getApplicationContext(),
"Tango Service out of date!", Toast.LENGTH_SHORT)
.show();
} catch (TangoErrorException e) {
Toast.makeText(main.getApplicationContext(),
"Tango Error! Restart the app!", Toast.LENGTH_SHORT)
.show();
}
}
}
The setTangoListeners() method called:
private void setTangoListeners() {
// Select coordinate frame pairs
framePairs.clear();
framePairs.add(new TangoCoordinateFramePair(
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE ,
TangoPoseData.COORDINATE_FRAME_DEVICE ));
mTango.connectListener(framePairs, new Tango.OnTangoUpdateListener() {
/**
* Callback called when new pose data is made available from the Tango
* #param tangoPoseData
*/
#Override
public void onPoseAvailable(final TangoPoseData tangoPoseData) {
if (tangoPoseData.baseFrame == TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE &&
tangoPoseData.targetFrame == TangoPoseData.COORDINATE_FRAME_DEVICE ) {
float[] transform = new float[16];
Matrix.setIdentityM(transform, 0);
NVector translationData = new NVector(
SCALE_FACTOR * tangoPoseData.getTranslationAsFloats()[TangoPoseData.INDEX_TRANSLATION_X],
SCALE_FACTOR * tangoPoseData.getTranslationAsFloats()[TangoPoseData.INDEX_TRANSLATION_Y],
SCALE_FACTOR * tangoPoseData.getTranslationAsFloats()[TangoPoseData.INDEX_TRANSLATION_Z]);
rotationQuat = new NVector((float) tangoPoseData.rotation[TangoPoseData.INDEX_ROTATION_X],
tangoPoseData.getRotationAsFloats()[TangoPoseData.INDEX_ROTATION_Y],
tangoPoseData.getRotationAsFloats()[TangoPoseData.INDEX_ROTATION_Z],
tangoPoseData.getRotationAsFloats()[TangoPoseData.INDEX_ROTATION_W]);
float[] quatMat = new float[16];
Matrix.setIdentityM(quatMat, 0);
quatMat = quaternionToMatrix(rotationQuat);
Matrix.multiplyMM(transform, 0, openGLConversion, 0, quatMat, 0);
transform[12] = translationData.getX();
transform[13] = translationData.getZ();
transform[14] = -1.f * translationData.getY();
float[] invertedTransform = new float[16];
Matrix.setIdentityM(invertedTransform, 0);
Matrix.invertM(invertedTransform, 0, transform, 0);
//main.displayMat(invertedTransform);
SceneCamera.instance().setEye(translationData);
SceneCamera.instance().set(invertedTransform);
//main.displayVals(tempPosition, rotationQuat);
}
}
/**
* Callback called when new depth data is made available from the tango
*
* #param tangoXyzIjData
*/
#Override
public void onXyzIjAvailable(final TangoXyzIjData tangoXyzIjData) {
Log.d("Depth Data", "Collected");
pointCloudBuffer = tangoXyzIjData.xyz;
}
/**
* Callback when new Image Frame is available for capture
* #param cameraID ID of the camera who has a fresh frame prepared
*/
#Override
public void onFrameAvailable(int cameraID) {
Log.d(TAG, "onFrameAvailable Called");
// Intentionally left empty
}
/**
* Callback when tango has an issue that needs addressing
* #param tangoEvent the event storing the data of the issue
*/
#Override
public void onTangoEvent(final TangoEvent tangoEvent) {
if (tangoEvent.eventKey.equals(TangoEvent.DESCRIPTION_FISHEYE_OVER_EXPOSED) ||
tangoEvent.eventKey.equals((TangoEvent.DESCRIPTION_COLOR_OVER_EXPOSED))) {
sendMessage("The Camera is overexposed. Please try facing somewhere with less direct light.");
}
if (tangoEvent.eventKey.equals(TangoEvent.DESCRIPTION_FISHEYE_UNDER_EXPOSED) ||
tangoEvent.eventKey.equals((TangoEvent.DESCRIPTION_COLOR_UNDER_EXPOSED))) {
sendMessage("Fisheye Lens is underexposed. Please try facing somewhere with more light.");
}
}
});
}
I hate to vomit code like this, but I've been trying on and off for weeks to get the depth sensing to work, but the onXYZijAvailable callback just refuses to be called, and I'm at the end of my rope.
One thing that might be an issue is that the app uses Vuforia for some extra Augmented Reality features, and has access to the color camera and camera preview, but I didn't see anything in the Tango documentation that would suggest that that might cause an issue.
Thanks much to anyone that can help me out.