I have a circular layout and there are "n" buttons in this layout. I start the animation on that layout when the activity starts.
When I click on any button the animation should stop and a dialog appear with the message, "You have clicked this 'XYZ' button".
The code I am using:
animation = AnimationUtils.loadAnimation(this, R.anim.rotate);
animation.setFillEnabled(true);
animation.setFillAfter(true);
findViewById(R.id.circle_layout).startAnimation(animation);
and the animation XML:
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="15000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" >
There is no pause in animation in android. I checked many questions relating to the same on StackOverflow but no luck. You can still give a try to pausing the Activity itself using this link which may help.
The link states the following:
Pause Your Activity
When the system calls onPause() for your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity and it will soon enter the Stopped state. You should usually use the onPause() callback to:
Stop animations or other ongoing actions that could consume CPU.
Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
There is no pause as posted. But you can mimic it.
This answer worked for me:
How do I pause frame animation using AnimationDrawable?
public class PausableAlphaAnimation extends AlphaAnimation {
private long mElapsedAtPause=0;
private boolean mPaused=false;
public PausableAlphaAnimation(float fromAlpha, float toAlpha) {
super(fromAlpha, toAlpha);
}
#Override
public boolean getTransformation(long currentTime, Transformation outTransformation) {
if(mPaused && mElapsedAtPause==0) {
mElapsedAtPause=currentTime-getStartTime();
}
if(mPaused)
setStartTime(currentTime-mElapsedAtPause);
return super.getTransformation(currentTime, outTransformation);
}
public void pause() {
mElapsedAtPause=0;
mPaused=true;
}
public void resume() {
mPaused=false;
}
}
Please note: this does not technically 'pause' the animation because it keeps continuously calling the transformation. But can keeps a persistent transformation that 'mimics' the same functionality.
I tried this with a RotateAnimation and worked just fine. But it will not lower the CPU/framerate when it is 'paused' as it does when you cancel the animation.
There is no great way to pause an animation mid-cycle.
You could subclass RotateAnimation and intercept the currentTime value in getTransformation and feed it the same time while you want your animation to be paused.
If you can afford to only support HC+, then you should look into using property animations instead of View animations.
Related
As the title says.
Specifically, I am writing an app that prints data to files over the course of runtime. I want to know when I can tell my PrintWriters to save the files. I understand that I can probably do autosave every X minutes, but I am wondering if Android Studio will let me save on close instead. I tried using onDestroy but the code block never executed. (To be precise, I started the app, did a few things, closed the app, clicked Recents, and swiped the app away. The debugger showed that the app never got to that code.)
My current solution attempts to catch the surrounding circumstances by checking for key presses but this only works for the back and volume buttons and not the home, recent, or power buttons.
#Override public boolean onKeyDown(int key, KeyEvent event) {
close();
return false;
}
There's a built in hook to the Activity lifecycle to save your state- onSaveInstanceState. There's even a bundle passed into you to save your state into for it to be restored (the matching function is onResumeInstanceState). And as a free bonus, if you call super.onSaveInstanceState and super.onRestoreInstanceState, it will automatically save the UI state of your app for all views with an id.
Please check the activity lifecycle:
https://developer.android.com/guide/components/activities/activity-lifecycle
Or if you're using a fragment:
https://developer.android.com/guide/fragments/lifecycle
Consider using one of these two:
#Override public void onStart() {
super.onStart();
close();
}
#Override public void onPause() {
super.onPause();
close();
}
I need to hide the content of my application when it goes to the background so sensitive information are not showing up on the android multitasking view.
It's been suggested to use the following line to hide the screen
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
It works fine.
However, this prevents the user from taking screenshot as well which is not an expected behavior for me. I want to let the user take screenshot of the app if they need to. What I don't want is Android to display the latest screen on the multitasking view.
Would it be possible to set the FLAG_SECURE only when the app goes in the background?
We've ended up with this solution which worked the best for us:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
}
You can use Activity Lifecycle Callbacks. Just call setVisiblity(View.INVISIBLE) on the views that you want to hide in the onPause() Callback and setVisiblity(View.VISIBLE) in onResume() Callback.
I have created a startup activity from where I am calling another activity which has a view pager and shows some introductory pages.
This app was taking time to load so I thought to display a progress dialog till the activity loads, but that progress dialog also appears few seconds later.
startup activity:
public class StartUpActivity extends AppCompatActivity {
boolean isUserFirstTime, login;
public static String PREF_USER_FIRST_TIME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isUserFirstTime = Boolean.valueOf(Utils.readSharedSetting(StartUpActivity.this, PREF_USER_FIRST_TIME, "true"));
Intent introIntent = new Intent(StartUpActivity.this, SlidingActivity.class);
introIntent.putExtra(PREF_USER_FIRST_TIME, isUserFirstTime);
ProgressDialog dialog = new ProgressDialog(StartUpActivity.this);
dialog.setMessage("Welcome to Mea Vita, please wait till the app loads.");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Here you can send the extras.
startActivity(new Intent(StartUpActivity.this,SlidingActivity.class));
// close this activity
finish();
}
}, 4000);
}
}
This doesn't happen every time,only sometimes. What can be the possible reason for this? how can I stop this?
Any solution? Thank you..
There is a strange issue with newly released Android Studio 2.0 (same issue in 2.1) first time of launching application take longer than usual (e.g. 2, 3 seconds or sometimes screen blinks or goes black) this issue happens only in debug mode and not effect your released APK.
A temporary solution to fix this is disabling instant run:
Settings → Build, Execution, Deployment → Instant Run and uncheck Enable Instant Run
First of all, make as rule to make all data loading in async tasks, you must check activity that you want to start where you load data.
The problem is in your second activity.
oncreate method should be used only to make findviews or start async tasks, don't load any in oncreate or in onstart or in onresume.
Probably you are loading high res images in sliding layout or you loading data in it.
There is another way, load all data in async task on first activity, then with ready data start second activity with already data loaded.
There are a few things that can load slowly.
Android need to read your code from storage and load the classes into ram.
I assume Utils.readSharedSetting(StartUpActivity.this, PREF_USER_FIRST_TIME, "true") reads from preferences. That's a file that you're reading from synchronously.
Actually launching the dialog takes a very small amount of time.
I'd suggest showing your loading inside the activity itself to minimize the work needed to render it.
Also, you can store PREF_USER_FIRST_TIME as a boolean instead of a String.
I am trying to write some Activity tests for an app, and one particular scenario that I want to test is that when I click a certain button, the Activity view updates accordingly. However, clicking the button causes a somewhat long running asynchronous task to start and only after that task is completed does the view change.
How can I test this? I'm currently trying to use the ActivityInstrumentationTestCase2 class to accomplish this, but am having trouble figuring out how to have the test 'wait' until the asynchronous part of the button click task is complete and the view updates.
The most common and simplest solution is to use Thread.sleep():
public void testFoo() {
TextView textView = (TextView) myActivity.findViewById(com.company.app.R.id.text);
assertEquals("text should be empty", "", textView.getText());
// simulate a button click, which start an AsyncTask and update TextView when done.
final Button button = (Button) myActivity.findViewById(com.company.app.R.id.refresh);
myActivity.runOnUiThread(new Runnable() {
public void run() {
button.performClick();
}
});
// assume AsyncTask will be finished in 6 seconds.
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals("text should be refreshed", "refreshed", textView.getText());
}
Hope this helps.
If you're using Eclipse, you could use the debugger by setting a breakpoint in the code that updates the view. You could also set some breakpoints in the long running task to watch and ensure that all your code is executing.
An alternative, write some log or console outputs in your long-running task and the view updater code, so you can see the progress without interrupting the thread by a debugger.
As a piece of advise, if its a long-running process, you should be showing a progress bar of some description to the user, so they aren't stuck there thinking "Is something happening?". If you use a progress bar with a maximum value, you can update it in your long-running task as it is running, so the user can see the activity going from 10% to 20%... etc.
Sorry if you were expecting some kind of jUnit-specific answer.
I ended up solving this by using the Robotium library's Solo.waitForText method that takes a string and timeout period and blocks until either the expected text appears or the timeout occurs. Great UI testing library.
Hi i'm using Rotating Progress Bar in my Android Music Plyer Application....I'm not able to stop it. While working with horizontal Progress bar i used handler to stop and start it.
But while working with Rotating One, The progress bar goes into Infinite Loop.....
Can you please suggest method to stop the indefinite loop. Thanks in advance.
How about using ProgressBar#dismiss() method?
EDIT: dismiss() is only for ProgressDialog. For ProgressBar you should toggle the Visibilty of the View.
If mHandler is a Handler bound to your UI thread and mProgress is your ProgressBar, you can have something like the following from inside the run method of your background thread:
mHandler.post(new Runnable() {
public void run() {
mProgress.setVisibility(View.INVISIBLE);
}
});
You can dismiss a ProgressDialog. A progressBar is just a view you can make set its visibility as visible or invisible based on your requirement
Drawable d = yourActivity.this.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
d.setBounds(progressbar.getIndeterminateDrawable().getBounds());
progressbar.setIndeterminateDrawable(d);