2016-02-19 2 views
0

Итак, я разработал приложение Android около года назад в Android Studio, чтобы позаботиться о некоторых вещах в моем колледже. Однако я никогда не «полностью закончил» его. Единственное, что мне не хватает, - это когда я нажимаю кнопку, запускает таймер и выводит строку. Однако, если я нажму еще одну кнопку до того, как этот таймер будет поднят, он скажет оба одновременно. В поиске в Интернете я не нашел точно, что искал, поэтому решил, что я открою его для сообщества Stackoverflow, и, возможно, вы можете вести меня в правильном направлении. Теперь для кода.Остановить Android CountDownTimmer при нажатии другой кнопки

package com.example.james.texttospeech; 



import android.os.Bundle; 
import android.app.Activity; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.view.View; 
import android.widget.EditText; 
import android.speech.tts.TextToSpeech; 
import android.speech.tts.TextToSpeech.OnInitListener; 
import android.content.Intent; 
import java.util.Locale; 
import android.widget.Toast; 
import android.os.CountDownTimer; 



public class MainActivity extends Activity implements OnClickListener, OnInitListener { 

    //TTS object 
    private TextToSpeech myTTS; 

    //status check code 
    private int MY_DATA_CHECK_CODE = 0; 

    //create the Activity 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //get a reference to the button element listed in the XML layout 
     Button speakButton = (Button)findViewById(R.id.speak); 


     //listen for clicks 
     speakButton.setOnClickListener(this); 

     //check for TTS data 
     Intent checkTTSIntent = new Intent(); 
     checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); 
     startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE); 


    } 

    //respond to button clicks 
    public void onClick(View v) { 

     //get the text entered 
     EditText enteredText = (EditText)findViewById(R.id.enter); 
     String words = enteredText.getText().toString(); 
     speakWords(words); 

    } 
    public void BRC (View view) { 
     new CountDownTimer(65000, 6000) { 

      public void onTick(long millisUntilFinished) { 
       String words1 = ("BRC will form up in" + millisUntilFinished/6000 + " minutes"); 
       speakWords(words1); 
      } 

      public void onFinish() { 
       String words2 = ("BRC will form up right away"); 
       speakWords(words2); 
      } 
     }.start(); 


} 


    public void SRC (View view1) { 

     new CountDownTimer(65000, 6000) { 

      public void onTick(long millisUntilFinished) { 
       String words3 = ("SRC will form up in" + millisUntilFinished/6000 +" minutes"); 
       speakWords(words3); 
      } 

      public void onFinish() { 
       String words4=("SRC will form up right away"); 
       speakWords(words4); 
      } 
     }.start(); 
    } 

    public void Taps (View view2) { 

     new CountDownTimer(65000, 6000) { 

      public void onTick(long millisUntilFinished) { 
       String words5 = ("Taps will sound in" + millisUntilFinished/6000 +" minutes"); 
       speakWords(words5); 
      } 

      public void onFinish() { 
       String words6=("Attention inside and outside of barracks the status in barracks is now Taps C C Q at the beginning of this turnout there was a status check"); 
       speakWords(words6); 
      } 
     }.start(); 
    } 

    public void Penalty_Tours (View view3) { 

     new CountDownTimer(65000, 6000) { 

      public void onTick(long millisUntilFinished) { 
       String words7 = ("P Tees will form up in" + millisUntilFinished/6000 +" minutes"); 
       speakWords(words7); 
      } 

      public void onFinish() { 
       String words8=("P Tees will form up right away"); 
       speakWords(words8); 
      } 
     }.start(); 
    } 

    public void Colors (View view4) { 

     String words9 = ("Colors Colors Colors"); 
     speakWords(words9); 
    } 

    public void PTT (View view5) { 

     new CountDownTimer(65000, 6000) { 

      public void onTick(long millisUntilFinished) { 
       String words10 = ("P T T will form up in" + millisUntilFinished/6000 +" minutes"); 
       speakWords(words10); 
      } 

      public void onFinish() { 
       String words11=("P T T will form up right away"); 
       speakWords(words11); 
      } 
     }.start(); 

    } 



    //speak the user text 
    private void speakWords(String speech) { 

     //speak straight away 
     myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null); 

    } 

    //act on result of TTS data check 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == MY_DATA_CHECK_CODE) { 
      if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { 
       //the user has the necessary data - create the TTS 
       myTTS = new TextToSpeech(this, this); 

      } 
      else { 
       //no data - install it now 
       Intent installTTSIntent = new Intent(); 
       installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); 
       startActivity(installTTSIntent); 
      } 
     } 
    } 

    //setup TTS 
    public void onInit(int initStatus) { 

     //check for successful instantiation 
     if (initStatus == TextToSpeech.SUCCESS) { 
      if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE) 
       myTTS.setLanguage(Locale.US); 
     } 
     else if (initStatus == TextToSpeech.ERROR) { 
      Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

Любая помощь была бы принята с благодарностью.

public void BRC(View view) { 
    int totaltime = 6500; 
    CountDownTimer mTimer = new CountDownTimer(totaltime, 6000) { 

     public void onTick(long millisUntilFinished) { 
      String words1 = ("BRC will form up in" + millisUntilFinished/6000 + " minutes"); 
      speakWords(words1); 
     } 

     public void onFinish() { 
      String words2 = ("BRC will form up right away"); 
      speakWords(words2); 
     } 
    }.start(); 

void SRC() { 
    mTimer.cancel(); 
} 

}

+0

http://stackoverflow.com/questions/27333742/how-do-i-prevent-my-countdowntimer-from-running-in-background/27333819#27333819 – codeMagic

+0

После того, как мой Android Студия завершает обновление, я посмотрю. –

+0

@codeMagic, когда я добавляю mTimer = new CountDownTimer, он говорит, что не может разрешить символ mTimer. –

ответ

0

В функции MainActivity, объявить переменную, чтобы определить статус каждого счетчика. В onTick() всех счетчиков, проверьте его на переменную

Надеюсь, что эта помощь.

public class MainActivity extends Activity implements OnClickListener, OnInitListener { 

//TTS object 
private Boolean isBRCRunning = false; 
private Boolean isPTTRunning = false; 
private static CountDownTimer myBRC; 
private static CountDownTimer myPTT; 

// 

    //respond to button clicks 
public void onClick(View v) { 

    // ..... 

    // If BRC button 
    if(BRC button){ 
     BRC(); 
     isBRCRunning = true; 
    } else if (PTT button){ 
     BRC(); 
     isBRCRunning = true; 
    } 

} 

public void BRC() { 
    myBRC = new CountDownTimer(65000, 6000) { 

     public void onTick(long millisUntilFinished) { 
      String words1 = ("BRC will form up in" + millisUntilFinished/6000 + " minutes"); 
      MainActivity.logForDebug(MainActivity.TAG, words1); 

      // Control other timer 
      if(isPTTRunning){ 
       myPTT.cancel(); 
       isPTTRunning = false; 
      } 
     } 

     public void onFinish() { 
      String words2 = ("BRC will form up right away"); 
      MainActivity.logForDebug(MainActivity.TAG, words2); 
     } 
    }.start(); 
} 

public void PTT() { 
    myPTT = new CountDownTimer(65000, 6000) { 

     public void onTick(long millisUntilFinished) { 
      String words1 = ("BRC will form up in" + millisUntilFinished/6000 + " minutes"); 
      MainActivity.logForDebug(MainActivity.TAG, words1); 

      // Control other timers 
      if(isBRCRunning){ 
       myBRC.cancel(); 
       isBRCRunning = false; 
      } 
     } 

     public void onFinish() { 
      String words2 = ("BRC will form up right away"); 
      MainActivity.logForDebug(MainActivity.TAG, words2); 
     } 
    }.start(); 
} 

}

+0

Когда я помещаю этот первый оператор if в onClick, он говорит, что он не может разрешить символ для BRC и PTT. Также он говорит, что BRC (представление) в MainActivity не может применяться к(). Это onClick выводит то, что есть в текстовом поле, оно не контролирует все клики. –

+0

Код в кнопке onClick - псевдокод. Для кнопки «BRC/PTT» в том случае, если вам нужно изменить в соответствии с вашим кодом, чтобы определить, была вызвана функция onClick() с кнопки BRC или кнопки PTT. –

Смежные вопросы