I am having an issue with Google Play Game Service where the leaderboard launches at random on launch and onresuming of the game from switching apps and selecting home. How can I change this behaviour?
if (isSignedIn()) {
startActivityForResult(getGamesClient().getAllLeaderboardsIntent(),
RC_UNUSED);
public int gameMode;
public static void showLeaderboard(int mode) {
me.gameMode = mode;
me.runOnUiThread(new Runnable() {
public void run() {
if (me.isSignedIn())
me.onShowLeaderboard();
else
me.SignIn();
}
});
}
public static void submitScore(final int score) {
me.gameMode = score / 1000000;
me.runOnUiThread(new Runnable() {
public void run() {
me.onSubmitScore(score % 1000000);
}
});
}
public void onShowLeaderboard() {
if (isSignedIn()) {
startActivityForResult(getGamesClient().getAllLeaderboardsIntent(),
RC_UNUSED);
} else {
showAlert(getString(R.string.signing_in));
this.SignIn();
}
}
public void onSubmitScore(int score) {
if (isSignedIn()) {
switch (gameMode) {
case 1:
getGamesClient().submitScore(getString(R.string.leaderboard1),
score);
break;
case 2:
getGamesClient().submitScore(getString(R.string.leaderboard2),
score);
break;
case 3:
getGamesClient().submitScore(getString(R.string.leaderboard3),
score);
break;
}
} else {
showAlert(getString(R.string.signing_in));
this.SignIn();
}
}
boolean verifyPlaceholderIdsReplaced() {
final boolean CHECK_PKGNAME = true; // set to false to disable check
// (not recommended!)
// Did the developer forget to change the package name?
if (CHECK_PKGNAME && getPackageName().startsWith("com.google.example.")) {
Log.e(TAG,
"*** Sample setup problem: "
+ "package name cannot be com.google.example.*. Use your own "
+ "package name.");
return false;
}
return true;
}
public void SignIn() {
if (!verifyPlaceholderIdsReplaced()) {
showAlert("Sample not set up correctly. See README.");
return;
}
// start the sign-in flow
beginUserInitiatedSignIn();
}
#Override
public void onSignInFailed() {
System.out.println("SignIn Failed!");
}
#Override
public void onSignInSucceeded() {
System.out.println("SignIn Successed!");
onShowLeaderboard();
}
I think it is because in your method 'onSignInSucceeded' you call 'onShowLeaderboard();' so everytime that the application is launched (first time or resumed) it will sign in and if the sign in process is successful then it will launch the method 'onShowLeaderboard();'
For a specific leader board you should use:
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(),
YOUR_LEADERBOARD_ID), REQUEST_LEADERBOARD);
instead of using:
startActivityForResult(getGamesClient().getAllLeaderboardsIntent(),
RC_UNUSED);
Related
During the Rewarded video play i want to disable the back button and set a minimum waiting time . is it possible to do?On which function should i change to complete my desired functionality?
here is my code
if (mAd.isLoaded()) {
mAd.show();
} else {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
and here is Rewarded video ads handling methods
private void loadRewardedVideoAds() {
if (!mAd.isLoaded()) {
mAd.loadAd(getResources().getString(R.string.rewardedvideoid), new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
// onBackPressed();
}
#Override
public void onRewardedVideoStarted() {
// onBackPressed();
}
#Override
public void onRewardedVideoAdClosed() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
loadRewardedVideoAds();
}
#Override
public void onRewardedVideoCompleted() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
Try below code
private boolean isVideoPlaying;
#Override
public void onRewardedVideoStarted() {
isVideoPlaying = true;
}
#Override
public void onRewardedVideoAdClosed() {
isVideoPlaying = false;
}
and than onBackPress() check, if the video is playing or not
#Override
public void onBackPressed() {
if (!isVideoPlaying)
super.onBackPressed();
}
Before implementing this, please read the policies carefully.
You must override the onBackPressed callback in activity and remove line super.onBackPressed(). then if the user taps the back button the activity will not close.
If you have no access to the Essay_Answer_Show activity check can you create another activity which extends that or clone library and tries to modify activity?
How can I register when the user open and close my app? I want to register every opening and every closing.
Lifecycle methods for example onResume() are not effective because the app use multiple activitys.
I can't find anything about that.
the best way to check if the app is exited or run is like this:
public class MyApplication extends Application {
public static final String LOG_TAG = "MyApp";
public boolean wasInBackground = true;
private AppSession appSession;
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000; // Time allowed for transitions
Application.ActivityLifecycleCallbacks activityCallbacks = new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityResumed(Activity activity) {
if (wasInBackground) {
//Do app-wide came-here-from-background code
appEntered();
}
stopActivityTransitionTimer();
}
#Override
public void onActivityPaused(Activity activity) {
startActivityTransitionTimer();
}
...
};
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(activityCallbacks);
}
public void startActivityTransitionTimer() {
this.mActivityTransitionTimer = new Timer();
this.mActivityTransitionTimerTask = new TimerTask() {
public void run() {
// Task is run when app is exited
wasInBackground = true;
appExited();
}
};
this.mActivityTransitionTimer.schedule(mActivityTransitionTimerTask,
MAX_ACTIVITY_TRANSITION_TIME_MS);
}
public void stopActivityTransitionTimer() {
if (this.mActivityTransitionTimerTask != null) {
this.mActivityTransitionTimerTask.cancel();
}
if (this.mActivityTransitionTimer != null) {
this.mActivityTransitionTimer.cancel();
}
this.wasInBackground = false;
}
private void appEntered() {
Log.i(LOG_TAG, "APP ENTERED");
appSession = new AppSession();
}
private void appExited() {
Log.i(LOG_TAG, "APP EXITED");
appSession.finishAppSession();
// Submit AppSession to server
submitAppSession(appSession);
long sessionLength = (appSession.getT_close() - appSession.getT_open())/1000L;
Log.i(LOG_TAG, "Session Length: " + sessionLength);
}
The onCreate method for the application class only runs once when the application is started. Maybe extend the application class and create some logic?
Or if you just record the application opening in the onCreate method of your first activity?
My code is here
I have test it on my device I also integrate this app on firebase.
but it never go to onRewarded it always call onRewardedFaild why sir?
can anyone help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this,APP_ID);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
// Create the "retry" button, which tries to show an interstitial between game plays.
mRetryButton = ((Button) findViewById(R.id.retry_button));
mRetryButton.setVisibility(View.INVISIBLE);
mRetryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGame();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
mShowVideoButton = ((Button) findViewById(R.id.watch_video));
mShowVideoButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
// Display current coin count to user.
mCoinCountText = ((TextView) findViewById(R.id.coin_count_text));
mCoinCount = 0;
mCoinCountText.setText("Coins: " + mCoinCount);
startGame();
}
#Override
public void onPause() {
super.onPause();
pauseGame();
mRewardedVideoAd.pause(this);
}
#Override
public void onResume() {
super.onResume();
if (!mGameOver && mGamePaused) {
resumeGame();
}
mRewardedVideoAd.resume(this);
}
private void pauseGame() {
mCountDownTimer.cancel();
mGamePaused = true;
}
private void resumeGame() {
createTimer(mTimeRemaining);
mGamePaused = false;
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
/* AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("40C4DDA8F53FFA9BA5B61261E0CA28AB") // Test devices don't work work with rewarded video ads.
.build();
mRewardedVideoAd.loadAd(AD_UNIT_ID, adRequest);*/
}
}
private void addCoins(int coins) {
mCoinCount = mCoinCount + coins;
mCoinCountText.setText("Coins: " + mCoinCount);
}
private void startGame() {
// Hide the retry button, load the ad, and start the timer.
mRetryButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setVisibility(View.VISIBLE);
loadRewardedVideoAd();
createTimer(COUNTER_TIME);
mGamePaused = false;
mGameOver = false;
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private void createTimer(long time) {
final TextView textView = ((TextView) findViewById(R.id.timer));
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mCountDownTimer = new CountDownTimer(time * 1000, 50) {
#Override
public void onTick(long millisUnitFinished) {
mTimeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("seconds remaining: " + mTimeRemaining);
}
#Override
public void onFinish() {
if (mRewardedVideoAd.isLoaded()) {
mShowVideoButton.setVisibility(View.VISIBLE);
}
textView.setText("You Lose!");
addCoins(GAME_OVER_REWARD);
mRetryButton.setVisibility(View.VISIBLE);
mGameOver = true;
}
};
mCountDownTimer.start();
}
private void showRewardedVideo() {
mShowVideoButton.setVisibility(View.INVISIBLE);
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" onRewarded! currency: %s amount: %d", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
addCoins(reward.getAmount());
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
I am using my Ad_Unit_ID Live not tested Device ID
I'm trying to write an app that will launch, or show a notification or a popup when another specific app goes to the background.
For example:
User launches app A
User uses app A
User puts app A in the background, either by pressing the home button or back button or launching another app
My app detects that and launches itself or shows a popup or whatever
Is there a way to do this and if there is, without killing the battery?
In your app A put the below code in a class:
public class Foreground implements Application.ActivityLifecycleCallbacks {
public static final long CHECK_DELAY = 500;
public static final String TAG = Foreground.class.getName();
public interface Listener {
public void onBecameForeground();
public void onBecameBackground();
}
private static Foreground instance;
private boolean foreground = false, paused = true;
private Handler handler = new Handler();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
private Runnable check;
/**
* Its not strictly necessary to use this method - _usually_ invoking
* get with a Context gives us a path to retrieve the Application and
* initialise, but sometimes (e.g. in test harness) the ApplicationContext
* is != the Application, and the docs make no guarantees.
*
* #param application
* #return an initialised Foreground instance
*/
public static Foreground init(Application application) {
if (instance == null) {
instance = new Foreground();
application.registerActivityLifecycleCallbacks(instance);
}
return instance;
}
public static Foreground get(Application application) {
if (instance == null) {
init(application);
}
return instance;
}
public static Foreground get(Context ctx) {
if (instance == null) {
Context appCtx = ctx.getApplicationContext();
if (appCtx instanceof Application) {
init((Application) appCtx);
}
throw new IllegalStateException(
"Foreground is not initialised and " +
"cannot obtain the Application object");
}
return instance;
}
public static Foreground get() {
if (instance == null) {
throw new IllegalStateException(
"Foreground is not initialised - invoke " +
"at least once with parameterised init/get");
}
return instance;
}
public boolean isForeground() {
return foreground;
}
public boolean isBackground() {
return !foreground;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
#Override
public void onActivityResumed(Activity activity) {
paused = false;
boolean wasBackground = !foreground;
foreground = true;
if (check != null)
handler.removeCallbacks(check);
if (wasBackground) {
Log.i(TAG, "went foreground");
for (Listener l : listeners) {
try {
l.onBecameForeground();
} catch (Exception exc) {
Log.e(TAG, "Listener threw exception!", exc);
}
}
} else {
Log.i(TAG, "still foreground");
}
}
#Override
public void onActivityPaused(Activity activity) {
paused = true;
if (check != null)
handler.removeCallbacks(check);
handler.postDelayed(check = new Runnable() {
#Override
public void run() {
if (foreground && paused) {
foreground = false;
Log.i(TAG, "went background");
for (Listener l : listeners) {
try {
l.onBecameBackground();
Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
startActivity(intent);
}
} catch (Exception exc) {
Log.e(TAG, "Listener threw exception!", exc);
}
}
} else {
Log.i(TAG, "still foreground");
}
}
}, CHECK_DELAY);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
}
Now in onCreate method of Application.class put the code:
#Override
public void onCreate() {
super.onCreate();
Foreground.init(this);
}
You have to set your app's package name in onActivityPaused() method.
Thanks
Do the code in onPause
#Override
protected void onPause() {
Toast.makeText(getApplicationContext(),"Background",Toast.LENGTH_LONG).show();
super.onPause();
}
So if the app goes in background, you will get toast.
Hope it helps..All the best
Try using Services. Read more on http://developer.android.com/guide/components/services.html
I'm trying to show some imageviews after the user has clicked on a button then wait for some time for the user to see which was the correct button to click then hide it again. Something like this:
User clicks on button giving his answer
-> Score is updated and correct answer is shown to user by setting the visibility of the imageview to visible
-> wait a moment for the user to be able to see which was the correct answer
-> hide the imageview again and load a new question.
So far I have this:
private void gameLoop(){
new Thread(new Runnable() {
#Override
public void run() {
while (isRunning) {
if (time > 0) {
sleepmillis(1000);
time--;
runOnUiThread(new Runnable() {
#Override
public void run() {
textViewTime.setText(time + " sec.");
}
});
} else
finishGame();
}
}
}).start();
}
private void sleepmillis(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
int givenAnswer = -1;
switch (view.getId()) {
case R.id.buttonFirst:
case R.id.imageViewFirst:
givenAnswer = 0;
break;
case R.id.buttonSecond:
case R.id.imageViewSecond:
givenAnswer = 1;
break;
case R.id.buttonThird:
case R.id.imageViewThird:
givenAnswer = 2;
break;
case R.id.buttonFourth:
case R.id.imageViewFourth:
givenAnswer = 3;
break;
}
processAnswer(givenAnswer);
}
private void processAnswer(int givenAnswer){
if (givenAnswer == answers[4]){
score += 5000;
correctAnswersInARow++;
if (correctAnswersInARow == 3)
score += 15000;
if (correctAnswersInARow == 6){
score += 30000;
correctAnswersInARow = 0;
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textViewScore.setText("Score: " + score);
}
});
showCorrectAnswer();
answers = gameData.getAnswers();
updateAnswers();
}
private void showCorrectAnswer(){
runOnUiThread(new Runnable() {
#Override
public void run() {
switch (answers[4]){
case 0:
ivCorrectFirst.setVisibility(View.VISIBLE);
break;
case 1:
ivCorrectSecond.setVisibility(View.VISIBLE);
break;
case 2:
ivCorrectThird.setVisibility(View.VISIBLE);
break;
case 3:
ivCorrectFourth.setVisibility(View.VISIBLE);
}
}
});
sleepmillis(400);
hideCorrectAnswers();
}
private void hideCorrectAnswers(){
runOnUiThread(new Runnable() {
#Override
public void run() {
ivCorrectFirst.setVisibility(View.INVISIBLE);
ivCorrectSecond.setVisibility(View.INVISIBLE);
ivCorrectThird.setVisibility(View.INVISIBLE);
ivCorrectFourth.setVisibility(View.INVISIBLE);
}
});
}
So the important part is in the showCorrectAnswer method, where I try to do what I explained here. Although the app waits 400 ms before loading a new question it doesn't show the correct answer.
imageView.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageView.setVisibility(View.INVISIBLE);
}
}, ms);
ms is time duration in milliseconds.