My Problem is I am Running one Method into Thread and after 30 Seconds I will display alertdialog and click on alertdialog's ok button i will stop current thread but problem is thread is not stop, following is my Code and sorry for bad english comunication
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
t.interrupt();
//t.stop();
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}
see this question...instead you can put a flag in run method.. and check whether to run or not to run the code in thread.
try this:-
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// t.interrupt();
t.stop();
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}
Related
When alertDialog.show gets called, it does pop up a dialog but it remains invisible. I have to tap on the screen until I happen to click the "OK" button that's on the alert even though it is not visibly showing.
public class RecordSignals extends Activity {
private ImageView pulseOxImage;
static AlertDialog poDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(saveInstanceState);
pulseOxImage = new ImageView(this);
pulseOxImage.setImageDrawable(ContextCompat
.getDrawable(this,R.drawable.pulse_ox_animation));
poDialog = new AlertDialog.Builder(this).create();
...
}
final Runnable callback = new Runnable() {
#Override
public void run() {
Thread thread = new Thread() {
#Override
public void run() {
...
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pulseOxArtifact >= 2 || pulseOxOutOfTrack >= 2 || pulseOxSensorAlarm >= 2) {
pulseOxStatus();
pulseOxImage.setVisibility(View.VISIBLE);
poDialog.show();
}
}
});
}
};
}
};
public void pulseOxStatus() {
poDialog.setView(pulseOxImage);
poDialog.setButton("OK", new DialogInterface.OnClicklistener() {
#Override
public void onClick(DialogInterface dialog, int which) {
poDialog.dismiss();
}
});
}
}
I have a CountDownTimer that dismisses a dialog popup window. I would like for this timer to restart if the user touches the screen. Here is what I have so far,
public class dataCapture extends Fragment implements OnClickListener {
...
MotionEvent event;
View.OnTouchListener touchListener;
#Override
public void onCreate(Bundle savedDataEntryInstanceState) {
super.onCreate(savedDataEntryInstanceState);
setRetainInstance(true);
}
...
#Override
public View onCreateView
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnHelpFilexml:
openHelpDialog();
break;
...
}
private void openHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody = (TextView) helpDialog.findViewById(R.id.tvHelpDialogBody);
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Here we go...\n" +
...
"This is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
// new countDownTimer(30000, 1000) {//makes popup go away after 30 secs
#Override
public void onTick(long millisUntilFinished) {//Do something every second...
}
#Override
public void onFinish() {//action at end of specified time
helpDialog.dismiss();
}
}.start();
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
countDownTimer.cancel();
countDownTimer.start();
}
return super.onTouchEvent(event);
}
helpDialog.show();
}
}
Any suggestions regarding how best to implement this function would be highly appreciated. Copious TIA.
UPDATE Got it. Solution below. Thanks.
public class dataCapture extends Fragment implements OnClickListener {
...
private static final int COUNTDOWN_TIME_MS = 30000;
Handler handlerHelpDialogTimer;
Runnable runnableHelpDialogDismissCountdown;
Dialog helpDialog;
private Dialog getHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Wheee, here we go\n" +
...
"this is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
tvHelpDialogBody.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View tvHelpDialogBody, MotionEvent event) {
cancelCountdown();
startCountdown();
return false;
}
});
helpDialog.show();
return (helpDialog);
}
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountdown();
}
synchronized private void startCountdown() {
handlerHelpDialogTimer.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handlerHelpDialogTimer.removeCallbacks(runnableHelpDialogDismissCountdown);
runnableHelpDialogDismissCountdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override
public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
runnableHelpDialogDismissCountdown = task;
return task;
}
Ditch the countdown timer. Instead use a handler, for example:
public class AwesomeActivity extends Activity {
private static final int COUNTDOWN_TIME_MS = 300000;
Handler handler;
Runnable countDown;
Dialog helpDialog;
#Override public void onCreate(Bundle b) {
super.onCreate(b);
handler = new Handler();
}
/* call cancelCountdown() in onPause* */
private Dialog getHelpDialog() { return /* fill in the details */ }
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountDown();
}
synchronized private void startCountDown() {
handler.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handler.removeCallbacks(countdown);
countdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
countDown = task;
return task;
}
}
Now in onTouch(MotionEvent e) you can cancel and start the countdown.
I'll leave it to you to figure out how to handle onPause and onResume :)
Furthermore, if you really wanted to, you could override a Dialog and put the Handler timer countdown logic inside that class, overriding show() to start the countdown and then add a method such as, restartTimer() you can call after a TOUCH_DOWN. If you do, you can then also override onSaveInstanceState and onRestoreInstanceState in the Dialog subclass, to cancel the callback, stash the time remaining, then pull out the time remaining and re-postdelay the countdown runnable with the remaining time.
I have been spending couple hours to try to update the textview inside the dialog, but failed.
When the option is clicked, there are new dialog is shown, and inside the dialog, there are textviews and button, when I click the button, the textview will be update.
Here is the code related to the button onClick listener:
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
final String currentNum = String.valueOf(i + 1);
Thread t = new Thread() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currentNum); //it is fine
currentNum.setText(currentNum); //it is the problem, the setText only work when the for loop is finished.
}
});
}
};
t.start();
}
}
});
Please let me know if you need more information. Thanks a lot in advance!
//it is a optionmenu
case R.id.action_refresh:
final TextView currentNum;
final ImageButton start;
String currentNum = Integer.toString(songList.size());
final Dialog lyricsAnalysis = new Dialog(this,R.style.cust_dialog);
lyricsAnalysis.requestWindowFeature(Window.FEATURE_NO_TITLE);
lyricsAnalysis.setContentView(R.layout.analysis);
lyricsAnalysis.setCancelable(true); //back button to cancel
lyricsAnalysis.setCanceledOnTouchOutside(true);
start = (ImageButton) lyricsAnalysis.findViewById(R.id.start);
//first value
currentNum.setText(String.valueOf(currentNum));
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTextView(lyricsAnalysis,i);
}
}
});
lyricsAnalysis.show();
lyricsAnalysis.getWindow().setLayout(600, 1000);
break;
}
return super.onOptionsItemSelected(item); }
public void updateTextView(Dialog dialog, int i) {
final TextView currentNum = (TextView) dialog.findViewById(R.id.currentNum);
currentNum.setText(Stri`enter code here`ng.valueOf(i));
//return;
}
Try this method. This may helps you. It's work for me.(But I am not use this in dialog)
public void updateTextView(String toThis) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
//return;
}
try like this
int elapsedtime=0;
boolean isTimerRunning=false;
Timer timerr;
inside onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//declare your textview here;
timerr=new Timer();
startTimer();
}
/*
* timer for displaying message bubble
*/
protected static void startTimer() {
isTimerRunning = true;
elapsedtime = 0;
// recordingseek.setProgress(0);
timerr.scheduleAtFixedRate(new TimerTask() {
public void run() {
// increase every sec
elapsedtime++;
mmHandler.obtainMessage(1).sendToTarget();
System.out.println("recording time" + elapsedtime);
if(elapsedtime==50)
timerr.cancel();
}
}, 1000, 2000);
};
public static Handler mmHandler = new Handler() {
public void handleMessage(Message msg) {
textview.setText(elapsedtime);
}
};
}
};
I use it to call another activity
Main.java
Intent intent = new Intent(this, Message_Note.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Message_Note.java :
public class Message_Note extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
}
}
How can i CLOSE the Message_Note Activity after 10 seconds ?? i should use a thread ?
After 100 MS, the activity will finish using the following code.
public class Message_Note extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 100);
}
}
You can use following approach.
Approach 1
int finishTime = 10; //10 secs
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
YourActivity.this.finish();
}
}, finishTime * 1000);
Approach 2
int FinishTime = 10;
int countDownInterval = 1000;
counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
public void onFinish() {
//finish your activity here
}
public void onTick(long millisUntilFinished) {
//called every 1 sec coz countDownInterval = 1000 (1 sec)
}
};
counterTimer.start();
You can use AlarmManager. See :
http://developer.android.com/reference/android/app/AlarmManager.html
and
Alarm Manager Example
Another way is just like this:
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Message_Note.this.finish();
}
}, 10000);
I have an application in which when the user starts the application a timer starts. After 10sec an AlertDialog pops up saying only 15 seconds reaming and displays a timer, and after 14 seconds it disappears. This works fine when on the first activity of the application. If the user passes from first Activty --> TimedNotify Activity the timer stops after 10seconds. onUserInteraction() in TimedNotify the timer restarts and works absolutely fine. Please assist me as to where I am going wrong.
public class FirstActivity extends TimedNotify{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.timercheck);
final Button btnstart2 = (Button) findViewById(R.id.btn);
btnstart2.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,
TimedNotify.class);
startActivity(intent);
}
});
}
}
public class TimedAlert extends Activity
{
static CountDownTimer timer1, timer2;
int flag = 0;
protected static final String TAG = null;
public static AlertDialog alert, alertdialog;
private static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView mCounter1TextField = (TextView) findViewById (R.id.mCounter1TextField);
// first timer set for 10sec
timer1 = new CountDownTimer(10000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
Log.v(TAG, "timer1 ticking");
mCounter1TextField.setText("Seconds left: "
+ formatTime(millisUntilFinished));
}
public void onFinish() {
//after 10sec display alert box and show timer
Log.v(TAG, "timer1 finished");
timer1.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(
TimedAlert.this);
builder.setTitle("Session Time Out");
builder.setMessage("00:15");
builder.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,int iwhich)
{
Intent in = new Intent(TimedAlert.this,FirstActivity.class);
//in case there are many events ..the intent should be passed to the last activity on clicking resume
in.setAction(Intent.ACTION_MAIN);
in.addCategory(Intent.CATEGORY_LAUNCHER);
onUserInteraction();
}
});
builder.setNegativeButton ("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,int iwhich)
{
timer2.cancel();
timer1.start();
}
});
alert = builder.create();
alert.show();
timer2 = new CountDownTimer(15000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
Log.v(TAG, "timer2 ticking");
alert.setMessage("Your Session will expire in 5 minutes . Timleft00:"+ (millisUntilFinished / 1000));
mCounter1TextField.setText("Seconds left: "+ formatTime (millisUntilFinished));
}
//after 15 sec dismiss alert box
public void onFinish() {
Log.v(TAG, "timer2 finished");
timer2.cancel();
alert.dismiss();
}
}.start();
}
}.start();
}
#Override
public void onBackPressed() {
Intent in = new Intent(TimedAlert.this, FirstActivity.class);
startActivity(in);
}
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
output = minutesD + " : " + secondsD;
return output;
}
public void onUserInteraction() {
super.onUserInteraction();
// Remove any previous callback
try {
Log.v(TAG, "user interacted");
timer1.start();
timer2.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.v(TAG, "paused");
onUserInteraction();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.v(TAG, "resumed");
onUserInteraction();
}
private void handleIntent(Intent intent) {
timer1.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.v(TAG, "stopped");
timer1.start();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.v(TAG, "started");
timer1.start();
}
}
OK, here are a few things I noted that might help you out:
public void onClick(DialogInterface dialog2, int iwhich) {
Intent in = new Intent(TimedAlert.this,
FirstActivity.class);
in.setAction(Intent.ACTION_MAIN);
in.addCategory(Intent.CATEGORY_LAUNCHER);
onUserInteraction();
}
You don't have a startActivity(in); after setting up all the parameters.
Why do onPause() and onResume() call onUserInteraction(), but onStart() and onStop() don't?
In fact, you should choose whether to use onPause() and onResume() only or onStart() and onStop(). Furthermore, onPause() or onStop() shouldn't restart the timers?
Thinking further about your reported problem, you say that it is when you are on your second activity that you have problems. Check out the lifecycle of an Activity - I suspect what might be happening is that you launch a new instance of your activity. Try setting your manifest to use android:launch mode="singleTask" for your activity.