How to logout from android application.? - java

here is my code.but if this runs my app closed from 60seconds.but when i again press app icon.its open as logged.how to close app with logout.?i added these in my service class.
public class BackgroundService extends Service {
private int interval3 = 10; // 10 seconds
private Handler mTimer3 = new Handler();
private Runnable mTask3 = new Runnable() {
public void run() {
mTimer3.postDelayed(this, interval3 * 1000L);
CountDownTimer timer = new CountDownTimer(10*1000, 1000) {
public void onTick(long millisUntilFinished) {
Log.w("Seconds remaining: ", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
};
timer.start();
}
};
public void onCreate() {
mTimer1.postDelayed(mTask1, interval1 * 1000L); // start the timer for the first time
mTimer2.postDelayed(mTask2, interval2 * 1000L); // start the timer for the first time
mTimer3.postDelayed(mTask3, interval3 * 1000L); // start the timer for the first time
}
please give me a suggestion.because we need to sign out from app when idle at more time.
thanks all

now its ok.i tried with activity class instead of service class and i added code to after login screen going page.now its working perrfect for me :-)
public class #MyActivityClass extends Activity {
//=============================================================================================================================
private Handler mTimer3 = new Handler();
private Runnable mTask3 = new Runnable() {
public void run() {
CountDownTimer timer = new CountDownTimer(10*1000, 1000) {
public void onTick(long millisUntilFinished) {
Log.w("Seconds remaining: ", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
//Here finally added finish(); and System.exit(0); methods
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
startActivity(intent);
finish();
System.exit(0);
}
};
timer.start();
mTimer3.postDelayed(this, interval3 * 1000L);
}
};
private int interval3 = 10*60; // 60 seconds
#Override
protected void onDestroy() {
if (mTimer3 != null) {
mTimer3.removeCallbacks(mTask3); // cancel the timer
}
}

Related

How To Destroy CoundownTimer in Java when the button is pressed?

I make a timer with a count time of 5 seconds, then when I press the exit button the counter automatically stops?
Here is my timer code:
public void startTimer(final long finish, long tick) {
CountDownTimer t;
t = new CountDownTimer(finish, tick) {
public void onTick(long millisUntilFinished) {
long remainedSecs = millisUntilFinished / 1000;
textTimer.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));// manage it accordign to you
}
public void onFinish() {
textTimer.setText("00:00");
Toast.makeText(FloatingVideoWidgetShowService.this, "Waktu Habis", Toast.LENGTH_SHORT).show();
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
cancel();
}
}.start();
}
And this is my code when pressing the stop / exit button :
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
}
});
How so when btn_deny is clicked Cuntdowntimer stops and does not force close?
Thanks.
You can't use onDestroy() to close your activity or fragment. Instead, you need to call finish().
To close the CountDownTimer, you need to make it a class scope variable. Prepare the timer at your startTimer then stop the timer by calling t.cancel() like the following code:
public class YourActivity extends Activity {
// Declare the variable to be accessed later.
CountDownTimer t;
...
public void startTimer(final long finish, long tick) {
t = new CountDownTimer(finish, tick) {
...
}.start();
}
private void yourOtherMethod() {
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(t != null) t.cancel();
...
}
});
}
}

I am trying to display a CountDownTimer on screen and I get "Only one looper can be created per thread" in my logcat

I'm a beginner in Android programming. I'm trying to display a timer for an upgrade in my game to show how long the upgrade will be activated for. In my collision flag I call Looper.prepare and start my thread class as the logcat suggested I do. How would I get this to run on one looper?
Here is the snippet that starts the thread.
BigGapUpgrade.java
public boolean playerCollectUpgrade(Player player){
if(Rect.intersects(rectangle, player.getRectangle())){
Looper.prepare();
bigGapUpgradeHandler.start();
}
return Rect.intersects(rectangle, player.getRectangle());
}
And here is my thread class
BigGapUpgradeHandler.java
public class BigGapUpgradeHandler extends Thread {
TimerTask scanTask;
Timer timer = new Timer();
#Override
public void run() {
Looper.prepare();
scanTask = new TimerTask() {
public void run() {
}
};
timer.schedule(scanTask, 0, 4000);
CountDownTimer countDownTimer = new CountDownTimer(4000, 100) {
#Override
public void onTick(long l) {
Log.i(TAG, "onTick: ");
}
#Override
public void onFinish() {
timer.cancel();
Log.i(TAG, "onFinish: ");
}
}.start();
Looper.loop();
}
}
After running it I get this error
W/System.err: java.lang.RuntimeException: Only one Looper may be created per thread
--Edit
Here is the solution I came up with.
-- Solution
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
CountDownTimer countDownTimer = new CountDownTimer(5000,100) {
#Override
public void onTick(long millisUntilFinished) {
millis = millisUntilFinished/100;
}
#Override
public void onFinish() {
}
}.start();
}
});
OK, So what you can do is just use a TimerTask. That creates it's own background thread for you do stuff:
// This TimerTask Updates the UI so it needs a reference to the Activity.
static class PowerUpTimerTask extends TimerTask
{
WeakReference<AppCompatActivity> mActivity;
long mInterval;
long mPeriod;
public PowerUpTimerTask(AppCompatActivity activity, long period, long interval)
{
mActivity = new WeakReference<>(activity);
mInterval = interval;
mPeriod = period;
}
#Override
public void run()
{
AppCompatActivity activity = mActivity.get();
if (activity != null)
{
final TextView timerTextView = activity.findViewById(R.id.timerTextView);
mPeriod -= mInterval;
if (mPeriod > 0)
{
// Set time remaining
activity.runOnUiThread(new Runnable()
{
#Override
public void run()
{
timerTextView.setText(String.valueOf(mPeriod));
}
});
}
else
{
// Out of time...clear the Text and stop the timer task.
activity.runOnUiThread(new Runnable()
{
#Override
public void run()
{
timerTextView.setText("");
}
});
Log.d(TAG, "Timer done. Canceling.");
cancel();
}
}
else
{
// Cancel this timer task since we don't have a reference to
// the Activity any more.
Log.d(TAG, "Lost reference to Activity. Canceling.");
cancel();
}
}
}
Then you can start your Timer task like so:
...
// Will count down from 10 by 1s.
mPowerUpTimerTask = new PowerUpTimerTask(this, powerUpTime, 1);
// Schedule for every second.
Timer t = new Timer();
t.scheduleAtFixedRate(mPowerUpTimerTask, 1000, 1000);
...
Here is a link to this running sample:
https://github.com/didiergarcia/TimerTaskExample
I think you have to use LocalBroadcastManager for the timing to continuously in loop. Please check below code for for that :-
private void startTimer() {
countDownTimer = new CountDownTimer(Constant.getInstance().ANSWER_TIME_IN_SECOND * 1000, 1000) {
public void onTick(long millisUntilFinished) {
remaininTimeInMillies = millisUntilFinished;
tvTimer.setText(getTime(Integer.parseInt(String.valueOf(millisUntilFinished))));
}
public void onFinish() {
Intent intent = new Intent(Constant.getInstance().TIMER_RECEIVER);
LocalBroadcastManager.getInstance(PatientDetailActivity.this).sendBroadcast(intent);
}
};
countDownTimer.start();
}
private String getTime(int milliSec) {
int minut = 0, second = 0;
minut = milliSec / 60000;
second = (milliSec - (minut * 60000)) / 1000;
String strMinute = "", strSecond = "";
if (minut < 10) {
strMinute = "0" + String.valueOf(minut);
} else {
strMinute = String.valueOf(minut);
}
if (second < 10) {
strSecond = "0" + String.valueOf(second);
} else {
strSecond = String.valueOf(second);
}
return strMinute + ":" + strSecond;
}
#Override
protected void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(timerBroadcast, new IntentFilter(Constant.getInstance().TIMER_RECEIVER));
super.onResume();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(timerBroadcast);
super.onDestroy();
}
Thanks and Hope that will help you

Auto next activity with countdown timer not working with cancel method

I try auto next activity with countdown timer but not work if use cancel method.
//Next Activity
CountDownTimer myCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Intent startActivity = new Intent(ActivityNew1.this,ActivityNew2.class);
startActivity(startActivity);
}
}.start();
myCountDownTimer.cancel();
Above java code auto next activity every 1s not working. And I try remove myCountDownTimer.cancel();
//Next Activity
new CountDownTimer(30000, 1000) {
public void onFinish() {
Intent startActivity = new Intent(ActivityNew1.this,ActivityNew2.class);
startActivity(startActivity);
finish();
}
public void onTick(long millisUntilFinished) {
}
}.start();
This java code work for auto next activity but auto next activity run after back to home, auto next not stop.
Solved
I just Add this code on backpress method.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent (this, MainActivity.class);
i.setFlags( Intent.FLAG_ACTIVITY_NO_HISTORY | FLAG_ACTIVITY_CLEAR_TOP );
startActivity( i );
finish();
finishAffinity();
System.exit( 0 );
}
Initialize a global boolean variable
boolean isPause = false;
Declare countdown timer
MyCountDownTimer myCountDownTimer;
Initialize CountDownTimer
myCountDownTimer = new MyCountDownTimer(5000, 1000);
myCountDownTimer.start();
Countdown Timer code
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
if(isPause){
startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class));
myCountDownTimer.cancel();
}
}
#Override
public void onFinish() {
// startActivity(new Intent(ConsumerHomeActivity.this, ForgotPasswordCustomerActivity.class));
}
}
When you want to cancel the timer, just do this
isPause = true;
and then the code in onTick will hit and you will be in next activity as countdown timer does not invoke onFinish method.

Timer Issue on Android Studio

I am having a problem with the Timer in my quiz Game. Essentially it's a multiple choice game and the player is timed on each question. I have the timer starting when the application starts and the player sees the first question. My issue is that if the player answers the question correctly or Incorrectly the timers starts giving random values, even though I reset the timer to 30 seconds on the onclick method. How do I get the timer to start at 30 seconds and countdown normally.
public class MainActivity extends AppCompatActivity {
//Views
TextView questionTextView;
TextView mscoreTextView;
TextView mtimerTextView;
Button mchoice1;
Button mchoice2;
Button mchoice3;
Button mchoice4;
//Constructors
private questions Question = new questions();
private Answers cAnswers = new Answers();
private choices Choices = new choices();
//Variables
private int questionNumber = 0;
private int mScore = 0;
private String correctAnswer;
public void onClick(View view) {
Button answer1 = (Button) view;
if(answer1.getText() == correctAnswer) {
mScore = mScore + 1;
Toast.makeText(getApplicationContext(), "CORRECT!!", Toast.LENGTH_SHORT).show();
mtimerTextView.setText("30s");
runTimer();
} else {
Toast.makeText(getApplicationContext(), "WRONG!!", Toast.LENGTH_SHORT).show();
mtimerTextView.setText("30s");
runTimer();
}
updateScore(mScore);
updateUI();
}
private void updateScore(int points) {
mscoreTextView.setText("" + points + "/" + Question.getLength());
}
public void runTimer() {
new CountDownTimer(30100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String tick = String.valueOf(millisUntilFinished/1000 + "s");
mtimerTextView.setText(tick);
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "TIME RAN OUT!!", Toast.LENGTH_LONG).show();
mtimerTextView.setText("0s");
updateUI();
}
}.start();
}
private void updateUI () {
if (questionNumber < Question.getLength()) {
questionTextView.setText(Question.getQuestion(questionNumber));
mchoice1.setText(Choices.getChoices(questionNumber, 1));
mchoice2.setText(Choices.getChoices(questionNumber, 2));
mchoice3.setText(Choices.getChoices(questionNumber, 3));
mchoice4.setText(Choices.getChoices(questionNumber, 4));
correctAnswer = cAnswers.getAnswer(questionNumber);
questionNumber ++;
} else {
Toast.makeText(getApplicationContext(), "This is the last question", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(MainActivity.this, HighScoreActivity.class);
//intent.putExtra("Score", mScore);
//startActivity(intent);
}
runTimer();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTextView = (TextView) findViewById(R.id.questionTextView);
mchoice1 = (Button) findViewById(R.id.choice1);
mchoice2 = (Button) findViewById(R.id.choice2);
mchoice3 = (Button) findViewById(R.id.choice3);
mchoice4 = (Button) findViewById(R.id.choice4);
mtimerTextView = (TextView) findViewById(R.id.timerTextView);
mscoreTextView = (TextView) findViewById(R.id.scoreTextView);
updateScore(mScore);
updateUI();
}
}
The thing is, you never really cancel a timer you've launched. Along with this, for every time you need a timer - you create a new one, which is not essential. The following must solve your problem:
You need to store CountDownTimer in a class field:
private CountDownTimer timer;
Then you can create it once on the start of app:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
timer = createTimer();
...
}
CreateTimer function:
public void createTimer() {
timer = new CountDownTimer(30100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
...
}
#Override
public void onFinish() {
...
}
}
}
So when you need to run timer you just call:
timer.start();
And when user gives an answer, you need to cancel timer first, then start it again:
public void onClick(View view) {
...
timer.cancel();
timer.start();
...
}
Also: you have some duplicated code in your OnClick() method. Regardless of user's answer correctness you need to run timer and set a value to mtimerTextView, so basically you want to do it outside of if-else construction.
You have to define a variable inside a CountDownTimer class.
public void runTimer() {
new CountDownTimer(30100, 1000) {
private int time = 30;
#Override
public void onTick(long millisUntilFinished) {
mtimerTextView.setText(time--+"s");
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "TIME RAN OUT!!", Toast.LENGTH_LONG).show();
mtimerTextView.setText("0s");
updateUI();
}
}.start();
}
Cancelable Timer
If you want your Timer cancelable you have to define it as a global variable.
private CountDownTimer timer; // global variable
start the timer by calling the below runTimer() method.
public void runTimer() {
timer = new CountDownTimer(30100, 1000) {
private int time = 30;
#Override
public void onTick(long millisUntilFinished) {
mtimerTextView.setText(time--+"s");
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "TIME RAN OUT!!", Toast.LENGTH_LONG).show();
mtimerTextView.setText("0s");
updateUI();
}
}.start();
}
You can cancel the timer by calling the below method.
public void stopTimer(){
if(timer != null){
timer.cancel();
}
}
Hope this will help

Nesting countdown timers in android

I want call CountDownTimer when one countdownTimer finishes it's execution.I tried calling one countdowntimer from another countdown timer's onFinish() method but it giving me nullpointer exception when I run this code.
public void First_Timer(){
Timer_Off =false;
dialog = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setCancelable(false);
dialog.setContentView(R.layout.backwash_timer_dialog);
final ToggleButton togglebtn_BW_timer = (ToggleButton)dialog.findViewById(R.id.togglebtn_BW_timer);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressBar1);
textView1 = (TextView)dialog.findViewById(R.id.textView1);
btn_BW_timer_stop = (Button)dialog.findViewById(R.id.btn_BW_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
textView1.setText("Time Up! ");
cdt.cancel();
Timer_Off =true;
dialog.dismiss();
// Call Second Timer Here
Second_Timer();
}
}.start();
btn_BW_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt.cancel();
bar.setProgress(0);
textView1.setText("0");
Timer_Off=true;
dialog.dismiss();
//onBackwashStopped();
}
});
dialog.show();
}
And Code for another timer is,
public void Second_Timer(){
Timer_Rinse_Off =false;
dialog_Rinse = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog_Rinse.setCancelable(false);
dialog_Rinse.setContentView(R.layout.rinse_timer_dialog);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressbar_Rinse);
txtRinse_TimerVal = (TextView)dialog.findViewById(R.id.txtRinse_TimerVal);
btn_Rinse_timer_stop = (Button)dialog.findViewById(R.id.btn_Rinse_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt_Rinse = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
txtRinse_TimerVal.setText("Time Up! ");
Timer_Rinse_Off =true;
dialog_Rinse.dismiss();
}
}.start();
btn_Rinse_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt_Rinse.cancel();
bar.setProgress(0);
txtRinse_TimerVal.setText("0");
Timer_Rinse_Off=true;
dialog_Rinse.dismiss();
//onBackwashStopped();
}
});
dialog_Rinse.show();
}

Categories