I have a problem with my app. I have created a button called "browse". By clicking it, the button performs a google search and the app is no longer visible. Additionally, I have a countdowntimer. Now I want that the countdowntimer pauses as long as the app is not visible.
Do you have any ideas?
I have already tried the methods onPause(); and onResume(); but its not properly working.
browse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String escapedQuery = null;
resume = true;
countDownTimer.cancel(); //I have no idea where to resume
try {
escapedQuery = URLEncoder.encode(begriff2, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Uri uri = Uri.parse("http://www.google.com/#q=" + escapedQuery);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
You can cancel it ,in onPause() , like this :
#Override
public void onPause() {
countDownTimer.cancel();
super.onPause();
}
Related
I'm developing an Android application and for some reason that has not yet been identified at random times it minimizes itself. I want to use the onPause callback function that is called when the app is minimized to programmatically reopen it.
As already mentioned, being able to make a rule to call the application reopening after a while so that it is not reopened immediately using Timer and TimerTask and a Boolean key:
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
public boolean wasInBackground;
private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 3000;
#Override
protected void onPause() {
super.onPause();
System.out.println("debug Pause/Resume: --- P A U S E ----");
startActivityTransitionTimer();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("debug Pause/Resume: ---- R E S U M E ---");
stopActivityTransitionTimer();
}
public void stopActivityTransitionTimer() {
if (this.mActivityTransitionTimerTask != null) {
this.mActivityTransitionTimerTask.cancel();
}
if (this.mActivityTransitionTimer != null) {
this.mActivityTransitionTimer.cancel();
}
this.wasInBackground = false;
}
public void startActivityTransitionTimer() {
this.mActivityTransitionTimer = new Timer();
this.mActivityTransitionTimerTask = new TimerTask() {
public void run() {
wasInBackground = true;
System.out.println("debug Pause/Resume: --- NEED REOPENE --");
}
};
this.mActivityTransitionTimer.schedule(
mActivityTransitionTimerTask,
MAX_ACTIVITY_TRANSITION_TIME_MS
);
}
I need to replace NEED REOPEN log with something that makes the app reopen.
I have already tried:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("package");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package","package.Activity"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Nothing worked, I'm inside an activity
I am trying to find a way to skip a flash screen by clicking on the screen of the activity. This is what I came to and it works. The problem is that after I click and the new activity is called, the boolean false default if runs again and the intent is called twice. What am I doing wrong?
RelativeLayout OnClickSkipScreen = (RelativeLayout)findViewById(R.id.SplashScreenView);
OnClickSkipScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OnClickSkip = true;
/*Loading.interrupt();
Intent SplashScreen = new Intent(SplashScreen.this, HomeScreen.class);
startActivity(SplashScreen);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();*/
}
});
Thread Loading = new Thread() {
#Override
public void run() {
if (!OnClickSkip) {
try {
sleep(2573);
Intent SplashScreen = new Intent(SplashScreen.this, HomeScreen.class);
startActivity(SplashScreen);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
} catch (Exception e) {
e.printStackTrace();
} finally {
finish();
}
} else if (OnClickSkip) {
try {
Intent SplashScreen = new Intent(SplashScreen.this, HomeScreen.class);
startActivity(SplashScreen);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
} catch (Exception e) {
e.printStackTrace();
} finally {
finish();
}
}
}
};
Loading.start();
}
use SharedPreference. Then think is whenever your class loads up it loads your boolean to its initial status which is false. so you will only meet one condition,all the time, which is the condition you are meeting now.
When i say persist, i mean you need to save your boolean state so as you can load it up from storage and check,with this your boolean will not be dependent on the initial state which is always false
so in your oncreate it could be this
SharedPreference sp = getPreference(0);
boolean OnClickSkip = sp.getBoolean("onclick",false);
now you can continue; if you want to save your boolean state
Editor e = sp.edit();
e.putBoolean("onclick",onClickSkip);
e.commit();
now continue to your codes
I am pulling my hair out! At one point in the last week, I had this working.
I have an Android app that I am trying to add in-ap billing to. I followed the sample TrivialDrive, and my code worked a few times. Now it doesn't.
I am creating a simple trivia game that has a number of free questions, and the option to upgrade to get more questions. When the user completes the list of free questions, they are taken to a "Game Over" screen where they can erase their answers and start again, or upgrade.
When I click the "Upgrade" button, I can make a successful purchase, but as soon as the Google "Payment Successful" dialog goes away, my activity is destroyed and I am sent back to my main activity.
When I try to go back and do my purchase again, my code catches the error ("You already own this item") and handles it appropriately. My code explains to the user that they already own the upgrade, and allows them to click a button to continue playing. So it looks like the OnIabPurchaseFinishedListener is firing at this point.
I have updated the Google helper code with the latest files.
Any help or suggestions as to where to look for answers is much appreciated.
Thanks.
This is the relevant code for my activity:
public class GameOverActivity extends BaseActivity
{
private IabHelper mHelper;
private String m_base64EncodedPublicKey;
private static String THE_UPGRADE_SKU = "upgrade52";
public static int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_over);
setTitle("Game Over");
Button butPlay = (Button) findViewById(R.id.buttonPlay);
butPlay.setVisibility(View.INVISIBLE);
PrepareIAB();
}
#Override
protected void onResume()
{
super.onResume();
CURRENT_ACTIVITY = ACTIVITY_GAME_OVER;
SetMainText();
}
#Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (mHelper != null)
{
mHelper.dispose();
mHelper = null;
}
}
catch (Exception e)
{
}
}
private void PrepareIAB()
{
m_base64EncodedPublicKey = "MyKey";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, m_base64EncodedPublicKey);
mHelper.enableDebugLogging( true, TAG);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess())
{
ShowMessage("There was an error connecting to the Google Play Store.");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
try
{
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data))
{
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
}
else
{
// Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
catch (Exception e)
{
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener =
new IabHelper.OnIabPurchaseFinishedListener()
{
public void onIabPurchaseFinished(IabResult result, Purchase purchase)
{
try
{
if (result.isFailure())
{
if (result.mResponse==7)
{
UpgradeComplete();
ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");
}
else
{
ShowMessage("Error purchasing: " + String.valueOf(result.mResponse));
UpgradeError();
return;
}
}
else if (purchase.getSku().equals(THE_UPGRADE_SKU))
{
UpgradeComplete();
ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");
}
else
{
ShowMessage("Something else happened. ");
}
}
catch (Exception e)
{
Log.e(TAG, e.getLocalizedMessage());
}
}
};
private void HideUpgrade()
{
try
{
Button btnUpgrade = (Button) findViewById(R.id.buttonUpgrade);
if (btnUpgrade != null)
{
btnUpgrade.setVisibility(View.INVISIBLE);
}
TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeFromGameOver);
if (txtMessage!=null)
{
txtMessage.setVisibility(View.INVISIBLE);
}
}
catch (Exception e)
{
}
}
public void onQuitButtonClick(View view)
{
finish();
}
public void onResetDBButtonClick(View view)
{
ConfirmResetDatabase();
}
private void ConfirmResetDatabase()
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
ResetDatabase();
Intent gameActivity = new Intent(getApplicationContext(), GameActivity.class);
gameActivity.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
// startActivityForResult(gameActivity, ACTIVITY_GAME);
startActivity(gameActivity);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to erase your score and start over?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
}
public void onUpgradeButtonClick(View view)
{
try
{
if (mHelper != null)
{
mHelper.launchPurchaseFlow(this, THE_UPGRADE_SKU, 10001, mPurchaseFinishedListener, m_TriviaAppInstance.AppInstallID());
}
else
{
ShowMessage("Unable to connect to Google Play Store.");
}
}
catch (Exception e)
{
ShowMessage("Unable to connect to Google Play Store.");
SendErrorMessage(e.getLocalizedMessage());
}
}
private void UpgradeComplete()
{
try
{
HideUpgrade();
Button butPlay = (Button) findViewById(R.id.buttonPlay);
if (butPlay!=null)
{
butPlay.setVisibility(View.VISIBLE);
}
TextView txtReset = (TextView) findViewById(R.id.txtGameOverRestDB);
if (txtReset!=null)
{
txtReset.setVisibility(View.INVISIBLE);
}
Button btnReset = (Button)findViewById(R.id.buttonResetDB);
if (btnReset!=null)
{
btnReset.setVisibility(View.INVISIBLE);
}
m_TriviaAppInstance.SetUpgradedStatus(true);
}
catch (Exception e)
{
}
//
}
private void UpgradeError()
{
try
{
Button butUpgrade;
butUpgrade = (Button) findViewById(R.id.buttonUpgrade);
butUpgrade.setVisibility(View.INVISIBLE);
TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeScreen);
txtMessage.setText(R.string.upgradeScreenTextError);
}
catch (Exception e)
{
}
}
public void onPlayButtonClick(View view)
{
Intent myIntent = new Intent(view.getContext(), GameActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(myIntent, ACTIVITY_GAME);
}
public void SetMainText()
{
TextView txt = (TextView) findViewById(R.id.txtScoreGlobal);
txt.setText(Integer.toString(m_TriviaAppInstance.getGlobal()) + "%");
SetPlayerScore(1);
if (m_TriviaAppInstance.getUpgradedStatus() == true)
{
HideUpgrade();
}
}
}
FYI: I think I have this figured out - for anyone else that may come across it.
The activity that I was using to launch "In App Billing" was called with a "FLAG_ACTIVITY_NO_HISTORY". I did this because I didn't want the user to be able to click to go back to this "Game Over" activity.
BUT, this causes grief with "In App Billing". So, make sure you don't try to launch "In App Billing" from an activity that has had the "FLAG_ACTIVITY_NO_HISTORY" set.
My original code:
private void GameOver()
{
m_TriviaAppInstance.setGameOver(true);
Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);
gameOver.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(gameOver);
}
Updated code:
private void GameOver()
{
m_TriviaAppInstance.setGameOver(true);
Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);
startActivity(gameOver);
}
Peace
I'm not high enough to comment, but bless you. I had
android:noHistory="true"
set in AndroidManifest.xml for my activity and was experiencing the same problem.
Took it out and IAB is working. Yay!
Do not forget that your IabHelper.OnIabPurchaseFinishedListener is called on a different thread and before onResume() is called on your Activity!
So your UpgradeComplete() or UpgradeError() can cause a crash on older devices (Crashed every time on my Gingerbread Sony Xperia Mini Pro and worked without any trouble on Samsung Galaxy S4 (Android 4.2.2)
Caused a 3 day delay on my game..
I have an ActivityInstrumentationTestCase2 with a test executing Button.click(). The Button should start an other Activity to do some work.
I think Button.performClick() is performed correctly, but the test is finishing before the other Activity is executed.
#UiThreadTest
public void test() {
Intent i = new Intent(this.myActivity, MyActivity.class);
myActivity.startActivity(i);
Button button = (Button) myActivity.findViewById(R.id.button);
button.performClick();
}
I tried the following which worked but i think this is rather a work-around than a good solution.
public void test() {
Intent i = new Intent(this.myActivity, MyActivity.class);
myActivity.startActivity(i);
Button button = (Button) myActivity.findViewById(R.id.button);
button.performClick();
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
Log.e("MyTest", e.getMessage());
}
}
IsnĀ“t there a better way?
This is my final solution:
public void test() {
Instrumentation instrumentation = getInstrumentation();
// Prepare a monitor for your activity
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(MyActivity.class.getName(), null, false);
// Start your activity manually
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), MyActivity.class.getName());
instrumentation.startActivitySync(intent);
Activity myActivity = getInstrumentation().waitForMonitor(monitor);
Button upSend = (Button) myActivity.findViewById(R.id.button);
upSend.performClick();
Log.d("MyTest", "button clicked");
//wait for SecondActivity to start (called by MyActivity)
monitor = instrumentation.addMonitor(SecondActivity.class.getName(), null, false);
Activity secondActivity = getInstrumentation().waitForMonitor(monitor);
int count = 0;
//wait until SecondActivity is finishing
while(!secondActivity.isFinishing()) {
Log.d("MyTest", "waiting - " + ++count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("MyTest",e.getMessage());
}
}
}
Thx again to Erik; now the second activity gets started by button and test is waiting for it to finish.
I have created a splash event and have it set to sleep for 3secs. Everything works fine but when you go to exit the application it takes you back to the splash. Is there a way to kill this with the code that I have or do I need to write this in a different manner.
public class splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openApp = new Intent("com.iqmobile.chris.IQMOBILEACTIVITY");
startActivity(openApp);
}
}
};
timer.start();
}
}
splash.this.finish(); after you start startActivity(openApp);
Intent openApp = new Intent("com.iqmobile.chris.IQMOBILEACTIVITY");
startActivity(openApp);
splash.this.finish();
Second Solution
in AndroidManifest file
<activity android:noHistory="true"
android:name=".splash" />
add finsh(); in code as :
Intent openApp = new Intent("com.iqmobile.chris.IQMOBILEACTIVITY");
startActivity(openApp);
splash.this.finsh();
mSplashThread = new Thread() {
#Override
public void run() {
try {
synchronized (this) {
wait(3000);
}
} catch (InterruptedException ex) {
}
finish();
Intent intent = new Intent();
intent.setClass(FirstActivity.this,
SecondActivity.class);
startActivity(intent);
}
};
mSplashThread.start();
}