Android Global Class,扩展Application,Helper Class

时间:2014-03-11 18:09:52

标签: android global-variables

关于使用Global变量类和扩展Application的另一个问题。希望它变化到足以不被视为重复。 我已经阅读了这些很棒的问题和答案。

Asynchronous programming best practices

How to use global class variables in android

虽然我理解这些与我当前的问题有什么关系,但由于我是一个新手,我有两个主要问题。

1-我不太确定如何应用这些解决方案,但我会尝试自己解决这个问题。

2-第二个也是最大的问题是,我的代码应该实际上甚至尝试迁移到全局类或帮助程序类。

所以我有3个类,Section1.java,Section2.java,Section3.java,基本上做同样的事情,以相同的方式,使用相同的方法,他们甚至使用几乎精确的xml布局(只有xml的名字)和每个xml中的drawable一起改变)。 唯一的区别是他们接受的正确结果。

关于我的第二个关注点,我的问题是在粘贴的代码下。

以下是来自Section1.java的代码(粗略的,looong spagetthi代码)

Section1.java

public class Section1  extends Activity implements OnClickListener, OnInitListener{

 private TextToSpeech myTTS;
  ListView lv;
  private ProgressDialog dialog;
  static final int check = 111;
  static final int checka = 222;
  static final int checkb = 333;
      TextView speak;
  private int MY_DATA_CHECK_CODE = 0;
  int counter_score;
  RatingBar rb_cooking;
  MediaPlayer ourSong;
     ImageView display,image1,image2,image3;
     int  gotLetterA, gotLetterB,gotLetterC
     int counter_score_a;
 int counter_score_b;
 int counter_score_c;

    @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
      setContentView(R.layout.section1);
            Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
        TextView speak = (TextView) findViewById(R.id.text_to_speech);
        ////////////////////////////////////

    counter_score=0;
    counter_score_this=0;
    counter_score_b=0;
    counter_score_c=0;
      image1 = (ImageView) findViewById(R.id.IVimage_1);
    image2 = (ImageView) findViewById(R.id.IVimage_2);
    image3 = (ImageView) findViewById(R.id.IVimage_3);

    initialize();


private void initialize() {
// TODO Auto-generated method stub
lv = (ListView)findViewById(R.id.lvVoiceReturn);
speak = (TextView) findViewById(R.id.text_to_speech);
Button play1 = (Button) findViewById(R.id.play_01);
Button play2 = (Button) findViewById(R.id.play_2);
Button play3 = (Button) findViewById(R.id.play_3);

 image1.setOnClickListener(this);
image2.setOnClickListener(this);
image3.setOnClickListener(this);

 play1.setOnClickListener(this);
play2.setOnClickListener(this);
play3.setOnClickListener(this);



public void speakClicked(View v) {
speak.setText("testing text");
speak(false);
}

public void speakJbClicked(View v) {
speak(true);
}
private void speak(boolean b) {
// get the text entered
TextView speak = (TextView) findViewById(R.id.texto_correcto);
speak.setText("test, spoken text");
String words = speak.getText().toString();
speakWords(words, b);
}

private void speakWords(String speech, boolean b) {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS, "true");
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, b ? hashMap : null);

}

    @Override
public void onClick(View v) {
    if (v.getId() == R.id.IVimage_1){
    Intent a = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    a.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    a.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    a.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(a, checka);
}else if(v.getId() == R.id.IVimage_2){
    Intent b = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    b.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    b.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    b.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(b, checkb);
}else if(v.getId() == R.id.IVimage_3){
    Intent c = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    c.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    c.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    c.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(c, checkc);
 }else if(v.getId() == R.id.play_01){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("a",TextToSpeech.QUEUE_FLUSH, null);
 }else if(v.getId() == R.id.play_2){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("b",TextToSpeech.QUEUE_FLUSH, null);
 }else if(v.getId() == R.id.play_3){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);/
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("c",TextToSpeech.QUEUE_FLUSH, null);

     @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
        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);
        myTTS.setPitch((float) .9);/////delete
        myTTS.setSpeechRate((float) 0.75);///delete maybe
        // }
        // else {
        // //no data - install it now
        // Intent installTTSIntent = new Intent();
        // installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        // startActivity(installTTSIntent);
        // }
      }
    if (requestCode == checka && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("hey") || results.contains("a") || results.contains("ay") || results.contains("add")|| results.contains("day")||results.contains("A")){
            counter_score ++;
            image1.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }

if (requestCode == checkb && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("b") || results.contains("be") || results.contains("boob")|| results.contains("dude")|| results.contains("B")){

            counter_score ++;
            image2.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }
if (requestCode == checkc && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("c") || results.contains("see") || results.contains("sea")|| results.contains("C")){
            counter_score ++;
            image3.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }

super.onActivityResult(requestCode, resultCode, data);



}
    @Override
public void onInit(int status) {
    // 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();
    // }
}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (myTTS !=null){
    myTTS.stop();
    myTTS.shutdown();


}
super.onDestroy();
}



public void onBackPressed() {
finish();
}

}

我会发布Section2.java,Section3.java,但代码中只有4件事情会发生变化。

1-xml布局,它本身就是一个精确的副本。

  

setContentView(R.layout.section1); //相应地更改为setContentView(R.layout.section2),setContentView(R.layout.section2)

2 - 接受的结果作为所说内容的正确答案。

  

if(results.contains(“hey”)|| results.contains(“a”)|| results.contains(“ay”)|| results.contains(“add”)|| results.contains(“ day“)|| results.contains(”A“)){//无论该类的正确答案是什么

3 - 进入下一个活动需要正确的数量问题

  

if(counter_score == 3){

4 - 发送我的包的活动

  

Intent nextAct = new Intent(Section1.this,Result_Section1.class);

我知道我可以为变量构建一个Global类。

最后我的问题。

当我阅读here时,我无法构建一个全局类来表示AlertDialog,因为如果我理解正确,对话框需要一个Context并且是View类的一部分。

Q1.我可以建立一个public class MyAlertDialogs extends View {来保存我的对话框吗?

当我阅读here时,我知道我可以构建一个Global类来处理OnclickListener。

问题2.我可以在全局课程中拥有SpeechRecognizer IntentTextToSpeech Intent吗?

1 个答案:

答案 0 :(得分:0)

回答Q1。在创建对象时,将视图类的上下文传递给对话框类。使用像

这样的构造函数
public DialogClass {
     final Context mContext;

     DialogClass(Context context) {
         mContext = context;
     }
}

并在从视图类传递上下文时创建它的对象。