I want to reload my activity after every 1 minute. I tried using handler for this... but problem is that when i press back key of device, it doesn't stop and goes into an infinite loop..
here is my code what i have done--
public class Chat extends Activity {
Handler handler;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.chat);
handler = new Handler();
Toast.makeText(getApplicationContext(), "again", 400).show();
doTheAutoRefresh();
}
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
public void run() {
Intent intent = getIntent();
startActivity(intent);
finish();
//doTheAutoRefresh();
}
}, 10000);
}
public void onPause() {
super.onPause();
}
}
You should do this to remove all handler's messages and callbacks:
public void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null);
}
Related
I have been trying to stop a handler in my onPause(). Despite of calling removeCallbacks(timeRunnable) or removeCallbacksAndMessages(timeRunnable), the handler is not stopped. I have seen many answers here. But nothing worked. I might be missing something here.
Code:
public Runnable timeRunnable = new Runnable() {
#Override
public void run() {
Log.d("Here is my task");
timeHandler.postDelayed(timeRunnable, 5000);
}
};
public void startTimeHandler() {
timeHandler.post(timeRunnable);
}
public void stopTimeHandler() {
timeHandler.removeCallbacks(timeRunnable);
}
#Override
protected void onPause() {
super.onPause();
stopTimeHandler();
}
I am using below code snippet to run a thread every 10 seconds and update UI based on the values received from Server, stop thread on onPause.
Declare below variables in your class:
public class ActivityPortfolio extends AppCompatActivity {
Handler handler = new Handler();
Runnable runnable;
int delay = 10*1000;
//---------
In your onResume:
#Override
protected void onResume() {
handler.postDelayed(new Runnable(){
public void run(){
doSomething();
handler.postDelayed(this, delay);
}
}, delay);
super.onResume();
}
onPause():
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable); // this alone didnt work as we are calling postDelayed() in background as well.
handler.removeCallbacksAndMessages(null);//after adding this it stops thread
}
I have my first activity that switch to the second one after 3 seconds and this works fine. The problem is that if i press the Home Button during this 3 seconds, the app reopen in the second activity. Is there a simple way to fix this?
Thanks in advance.
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
switchActivities();
}
#Override
public void onBackPressed(){
}
public void switchActivities() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
finish();
}
}, 3000);
}
}
EDIT:
Maybe I wasn't clear, I do not want the app to reopen once I press the home button. How can I do this?
This is because you don't clear your delayed callback. You can fix it in this way:
private Handler handler = new Handler();
public void switchActivities() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
finish();
}
}, 3000);
}
public void onStop() {
super.onStop();
handler.removeCallbacksAndMessages(null);
}
You just have to cancel your Handler when you leave your first activity before the second one opens.
public class StartActivity extends AppCompatActivity {
Runnable nextActivityRunnable;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
switchActivities();
}
#Override
public void onBackPressed(){
}
public void switchActivities() {
nextActivityRunnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
finish();
}
};
handler = new Handler();
handler.postDelayed(nextActivityRunnable, 3000);
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(nextActivityRunnable);
}
}
So I have this code, that has a countdown timer in a service with a 10 second timer. What I want to do is in the onFinish() method I want to launch the Activity (which is called MainActivity) automatically even when I am outside the app.
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
Try This to open your main activty after 10 second.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// launch your main activity here and finish your current activity
}
}, 10000);
}
Probably you will have to override lifecycle method's and also use PARTIAL_WAKE_LOCK to keep cpu running untill you finish execution, in case user lock screen.
If you are inside a service then simply launch you activity using intent. Put this code in your onFinish() method:
Intent i = new Intent();
i.setClass(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
You neet to pass an activity context to your TimeDisplayTimerTask :
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
private Activity mActivity;
public TimeDisplayTimerTask(Activity activity){
mActivity = activity;
super();
}
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
if (activity != null {
Intent startIntent = new Intent(activity, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startIntent);
}
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
I created two Activities "SplashActivity and AuthenticationActivity" When I start the app it loads the splash screen for 5 seconds and then it moves on to AuthenticationActivity. My problem is that when I run the app, it loads the splash screen, but within 5 seconds when I click the back button, SplashActivity exits, and immediately AuthenticationActivity appears in the foreground.
Does anyone know how to make it so when I click the back button, my app exits?
Here's my code so far:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread splashTimer = new Thread(){
public void run(){
try{
sleep(5000);
startActivity(new Intent(SplashActivity.this,AuthenticationActivity.class));
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
}
}
};
splashTimer.start();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}}
Timer timer;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
timer = new Timer();
timerTask = new TimerTask()
{
#Override
public void run()
{
//Start your activity here
}
};
timer.schedule(timerTask,2500);
}
#Override
public void onBackPressed() {
super.onBackPressed();
timer.cancel();
}
or you can use Handler also
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
handler = new Handler();
runnable = new Runnable()
{
#Override
public void run()
{
//start your activity here
}
};
handler.postDelayed(runnable, 5000);
}
#Override
public void onBackPressed() {
super.onBackPressed();
handler.removeCallbacks(runnable);
}
I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).
My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.
How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)
Thanks for helping
Here my Code of my MainActivity:
package com.example.parkourspots;
public class MainActivity extends Activity {
private ViewTreeObserver vto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
vto = myLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
});
}}
Check this code.
package com.example.parkourspots;
public class MainActivity extends Activity {
private static int TIME_OUT = 4000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, ActivityTwo.class);
startActivity(i);
finish();
}
}, TIME_OUT);
}
});
You can try:
public class MainActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.postDelayed(new Runanble() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); // 4 seconds
}
}
In addiction, you may add this for your second activity declaration in AndroidManifest: android:finishOnTaskLaunch="true"
never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive.
But this is an fast and alternative solution for your problem.
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}
private void doStuff() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}
Then 5 seconds after the intent must start.
But i recommend async task
1)Sleeping 500 only sleeps for .5 seconds. So it would blink quickly anyway
2)Sleeping doesn't allow the thread to get back to the looper, so it freezes your UI. This means it won't update and draw anyway. Use a timer instead. Or posting a message to a handler would be acceptable here.
The problem is you're only sleeping for 500 milliseconds (half of one second), so it makes sense that it happens seemingly-immediately. You're also going to want to remove the OnGlobalLayoutListener after it's called. Here's an example of an approach that should work for you:
final Handler handler = new Handler(); // Create a Handler on the main Thread
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
removeOnGlobalLayoutListener(vto, this);
handler.postDelayed(new Runnable(){
public void run(){
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); //Post back to the main Thread after 4000 mils (4 seconds)
}
});
#SuppressLint("NewApi")
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
else v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
Proper and short solution
Make a handler and give them a delay to call back itself:
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 1s
}
}, 1000);
Remember that 1 sec = 1000 milliseconds
Adjust time with that formula.
Happy Coding.