Hello im working with an jumpingApp that will count how many times you are jumping and im using accelorometer sensor.
The problem i got is that i don't really know how to put the delay so it is perfect, sometimes a jump counts as 2 jump sometimes it doesn't register and sometimes it works good. I would like to have around 0.4sec on every count jump.
private TextView textView;
private TextView text;
private SensorManager sensorManager;
double ax,ay,az;
boolean newJumpAccepted = true;
int numbersOfJumps = 0;
long startTime = 0;
int count;
MediaPlayer mediaPlayer;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
if(millis>400){
newJumpAccepted = true;
} else {
newJumpAccepted = false;
}
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerHandler.postDelayed(this,500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
#Override
public void onSensorChanged(SensorEvent event){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String result = "";
double d = Math.round(event.values[1]);
float threshold = preferences.getFloat("hello", 11);
if (d != 0 && d >= threshold && newJumpAccepted){
count++;
}
Log.i("hej", String.valueOf(d));
text.setText("Jump made" + " " + count + " " + d);
text.invalidate();
startTime();
}
private void startTime() {
if(newJumpAccepted) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
newJumpAccepted = false;
}
}
Timer timer;
MyTimerTask myTimerTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
if(timer != null){
timer.cancel();
}
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 400, 400);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!newJumpAccepted) {
text.setText(String.valueOf(count));
newJumpAccepted = true;
}
}
});
}
}
Related
I'm creating a timer app that utilizes a thread. When I exit the app using the home button the timer is running fine. Usually, when the time is up a dialog is launched that asks the user for some input. This works completely fine if the app is in its onResume() state, however when the app is in its onStop() state the dialog will not launch and an error is thrown.
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
How can I make it so that when the time is up and the app is NOT in the foreground the dialog is still launched. My initial thought was to save the time remaining in the bundle, but the time remaining is changing for every single tick. Then I thought about storing a boolean in the bundle mTimeRunning. However, when the time is up this value must also change. So now I'm drawing a blank. What can I possibly do so that the dialog is launched when the app is not in the foreground?
TimerActivity.java
public class TimerActivity extends AppCompatActivity implements TimeDialogFragment.sendMinutes,
TimeFinishDialogFragment.sendResponse, BreakFinishDialogFragment.userResponse {
// Variable to log activity state
private static final String TAG = "TimerActivity";
private static final boolean DEBUG = true;
// ^^ Variable used to log acitivty state
private Handler mHandler;
private Runnable mRunnable;
//private static final long START_TIME_MILLISECONDS = 600000;
// Below start time is for development purposes only
private static long mStartTime = 10000;
private long mTimeRemaining = mStartTime;
private boolean mTimeRunning;
private boolean mBreakTime = false;
private ProgressBar mTimeBar;
private TextView mTime;
private Button mStartPause;
private Button mSetTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
if(DEBUG) Log.d(TAG, "+ onCreate() +");
mHandler = new Handler();
mTimeBar = findViewById(R.id.time_bar);
mTime = findViewById(R.id.text_view_time);
mStartPause = findViewById(R.id.button_start_pause);
mSetTime = findViewById(R.id.button_set_time);
updateCountDownText();
mTimeBar.setMax((int) mTimeRemaining);
mSetTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//FragmentManager manager = getSupportFragmentManager();
DialogFragment setTime = new TimeDialogFragment();
setTime.show(getFragmentManager(),"SET_TIME_DIALOG");
}
});
mStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mTimeRunning){
//pauseTimer();
mTimeRunning = false;
mStartPause.setText("Start");
mHandler.removeCallbacks(mRunnable);
}else{
//startTimer();
timer();
}
}
});
}
// Using a handler + anon runnable
private void timer(){
mRunnable = new Runnable() {
#Override
public void run() {
mTimeRunning = true;
mStartPause.setText("Pause");
mTimeRemaining = mTimeRemaining - 1000;
updateCountDownText();
mTimeBar.incrementProgressBy(1000);
if(mTimeRemaining > 0) {
mHandler.postDelayed(this, 1000);
}else{
// if breaktime is false
if(!mBreakTime) {
DialogFragment dialog = new TimeFinishDialogFragment();
dialog.show(getFragmentManager(),"TIME_FINISH_DIALOG");
mTimeRunning = false;
}else{
// launch break time up dialog.
mBreakTime = false;
DialogFragment dialog = new BreakFinishDialogFragment();
dialog.show(getFragmentManager(), "BREAK_FINSIH_DIALOG");
}
}
}
};
mHandler.postDelayed(mRunnable,1000);
}
public void updateCountDownText(){
int min = (int) (mTimeRemaining / 1000) / 60;
int sec = (int) (mTimeRemaining / 1000) % 60;
String formattedString = String.format(Locale.getDefault(), "%02d:%02d", min, sec);
mTime.setText(formattedString);
}
public void setCountDownText(long time){
int min = (int) (time / 1000) / 60;
int sec = (int) (time / 1000) % 60;
String formattedString = String.format(Locale.getDefault(), "%02d:%02d", min, sec);
mTime.setText(formattedString);
}
#Override
public void userTime(int minutes) {
TimerActivity.mStartTime = (minutes * 60) * 1000;
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
setCountDownText(mTimeRemaining);
}
#Override
public void sendResponse(int val) {
if(val == -1){
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
mStartPause.setText("Start");
}else if(val == 1) {
mBreakTime = true;
mTimeRemaining = 15000;
mTimeBar.setMax((int) mTimeRemaining);
setCountDownText(mTimeRemaining);
mTimeBar.setProgress(0);
mStartPause.setVisibility(View.INVISIBLE);
timer();
}else {
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
timer();
}
}
#Override
public void userResponse(int val) {
if(val < 0) {
// user clicked cance
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
mStartPause.setText("Start");
}else {
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
timer();
}
mStartPause.setVisibility(View.VISIBLE);
}
TimeFinishedDialog.java
public class TimeFinishDialogFragment extends DialogFragment implements View.OnClickListener{
private Button mCancel;
private Button mSkip;
private Button mStartBreak;
private sendResponse mResponse;
interface sendResponse{
void sendResponse(int val);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//return super.onCreateDialog(savedInstanceState);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.time_finish_dialog_fragment, null, false);
mCancel = view.findViewById(R.id.button_cancel);
mSkip = view.findViewById(R.id.button_skip);
mStartBreak = view.findViewById(R.id.button_start_break);
mCancel.setOnClickListener(this);
mSkip.setOnClickListener(this);
mStartBreak.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Start Break?");
AlertDialog dialog = builder.create();
dialog.setContentView(view);
return dialog;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.button_cancel:
mResponse.sendResponse(-1);
getDialog().dismiss();
break;
case R.id.button_skip:
mResponse.sendResponse(0);
getDialog().dismiss();
break;
case R.id.button_start_break:
mResponse.sendResponse(1);
getDialog().dismiss();
break;
default:
break;
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mResponse = (sendResponse) getActivity();
}catch (ClassCastException e){
System.out.println("Error: " + e);
}
}
}
when the time is up and the app is NOT in the foreground the dialog is still launched
You should not be doing this since this will interrupt the user from doing other work which they might be doing at that time and this can be irritating.
What can I possibly do so that the dialog is launched when the app is not in the foreground?
You can show the dialog only the user is actively using your application or you can fall back to show a notification when the user is not using the app.
And if you desperately want to show a dialog, you can try a dialog themed activity
I have a countdown timer that i want to implement on finish method or some kind of code so that when the timer stops, the text views change to Time's up and another method is initiated (in the activity).
To clarify, the timer is given a starting number that counts down from, to zero in format of xx:xx.
The class of the timer :
public class countdown_timer {
private long pls;
private long millisInFuture;
private long countDownInterval;
private boolean status;
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
this.millisInFuture = pMillisInFuture;
this.countDownInterval = pCountDownInterval;
this.pls = pMillisInFuture;
status = false;
Initialize();
}
public void Stop() {
status = false;
}
public void Reset() {
millisInFuture = pls;
}
public long getCurrentTime() {
return millisInFuture;
}
public void Start() {
status = true;
}
public void Initialize()
{
final Handler handler = new Handler();
Log.v("status", "starting");
final Runnable counter = new Runnable(){
public void run(){
long sec = millisInFuture/1000;
if(status) {
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain");
millisInFuture -= countDownInterval;
handler.postDelayed(this, countDownInterval);
}
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
handler.postDelayed(this, countDownInterval);
}
}
};
handler.postDelayed(counter, countDownInterval);
}
The activty that the timer is used:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_game_2);
//...find views
mycounterup = new countdown_timer(startcard, 1000);
mycounterdown = new countdown_timer(startcard, 1000);
RefreshTimer();
mycounterdown.Start();
public void RefreshTimer()
{
final Handler handler = new Handler();
final Runnable counter = new Runnable(){
public void run(){
int minutes_up_start = (int) (mycounterup.getCurrentTime() / 1000) / 60;
int seconds_up_start = (int) (mycounterup.getCurrentTime() / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
card_2_up.setText(time_2_up_start_formatted);
int minutes_down_start = (int) (mycounterdown.getCurrentTime() / 1000) / 60;
int seconds_down_start = (int) (mycounterdown.getCurrentTime() / 1000) % 60;
String card_2_down_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_down_start, seconds_down_start);
card_2_down.setText(card_2_down_start_formatted);
handler.postDelayed(this, 100);
}
};
handler.postDelayed(counter, 100);
}
You can use CountDownTimer:
new CountDownTimer(endsIn * 1000, 1000) {
public void onTick(long millisUntilFinished) {
timerTextView.setText(String.valueOf(millisUntilFinished/1000);
}
public void onFinish() {
}
}.start();
OR:
extend CountDownTimer class:
public class countdown_timer extends CountDownTimer {
TextView textView;
#Override
public void onTick(long millisInFuture) {
long sec = millisInFuture/1000;
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
}
}
#Override
public void onFinish() {
if(textView != null){
// change text in your textview
}
}
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
}
public countdown_timer(TextView textView, long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
this.textView = textView;
}
}
here is a two constructors, one of them is the same as is in your example and in second one you can pass also TextView object and use it in onFinish() method.
UPDATE 2:
Here is CountDownTimer in the Activity:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 1000) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
UPDATE 3: if last tick is one, not zero change count down interval to 500 instead of 1000:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 500) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
NOTE: take a look at this answer
First, extend CountDownTimer in your timer class.
public class countdown_timer extends CountDownTimer {
}
This allows you to implement some methods.
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
}
Also you must implement constructor that matches super class. You can also add some additional parameters. For example TextView
TextView textView;
public countdown_timer(long millisInFuture, long countDownInterval, TextView txt) {
super(millisInFuture, countDownInterval);
textView = txt;
}
The onFinish() is what you want. Also make sure you are using this class as a CountDownTimer. Then you will be able to start your timer.
Hope it helps.
public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.
Iam making an android app which monitor voice in which when the voice loudness exceed a user defined threshold the app dial a specific number .
i done making voice monitoring and compared the highest value with the threshold then dialling the number .everything goes right except when the app returned after the call i find the monitoring isnt right , as the mic sensitivity is very week (measurement is very low ) i have to restart the app to obtain the right measurement , the second question here i make the comparison of the threshold and the last value of sound in the handler at the bottom , is this the right way ? thanks in advanceThis is the App image
Below is The Main activity
public class MainActivity extends AppCompatActivity {
private static final int sampleRate = 11025;
private static final int bufferSizeFactor = 10;
private Button Stop;
private ProgressBar On;
private Button Start;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private TextView textView;
volatile int threshold;
TextView testtextview;
private boolean clicked ;
private Handler handler = new Handler();
private int lastLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threshold = 20000;
//progressbar detect voice
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
//text displaying progress par value
textView = (TextView) findViewById(R.id.textView1);
testtextview = (TextView) findViewById(R.id.textViewtest);
if (audio != null) {
audio.stop();
audio.release();
audio = null;
handler.removeCallbacks(update);
} else {
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.removeCallbacks(update);
handler.postDelayed(update, 25);
}
//seekbar let user choose threshhold
SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar);
//text displayin user choice
final TextView textViewuser = (TextView) findViewById(R.id.textView3);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewuser.setText("" + i + "/32676");
threshold = i ;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Stop = (Button) findViewById(R.id.dummy_buttonstop);
On = (ProgressBar) findViewById(R.id.progressBar11);
Start = (Button) findViewById(R.id.dummy_button);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Start.setVisibility(View.GONE);
On.setVisibility(View.VISIBLE);
clicked = true;
}
});
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
clicked = false;
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
}
while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
if (audio != null) {
audio.release();
audio = null;
handler.removeCallbacks(update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
textView.setText(lastLevel + "/" + level.getMax());
if (clicked) {
if (lastLevel > threshold) {
clicked=false;
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
String url = "tel:01224271138";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//recreate();
}
}
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};
I got a problem with CountDownTimer's StartButton: the timer doesn't start after pressing the button. How do I fix that?
I want to start the timer by pressing button buttonCount.
Can someone help me please?
int clicks = 0;
TextView textCount;
ImageButton buttonCount;
int guessCount =0;
boolean started = false;
boolean timerProcessing = false;
private CountDownTimer count;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start();
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
It seems to me this is what you really want to do:
private int clicks = 0;
private TextView textCount;
private ImageButton buttonCount;
private int guessCount = 0;
private CountDownTimer count; // RENAMED
private boolean started = false; // FALSE.
private boolean timerProcessing = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) { // MOVED UP
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start(); // START COUNTDOWN TIMER
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
And if you really want to start another CountDownTimer than the one you create at the bottom (named count). Then you need to instantiate it and set its behaviour, just like you do for the other CountownTimer.
Also, all the variables you use need to be created before (textic, oldscore)