Advertisement
mmayoub

Horse Race with speech

Sep 25th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.96 KB | None | 0 0
  1. AutoSeekBar.java
  2. ----------------
  3. package com.example.mohamadpc.horserace;
  4.  
  5. import android.content.Context;
  6. import android.graphics.Bitmap;
  7. import android.graphics.Color;
  8. import android.graphics.drawable.BitmapDrawable;
  9. import android.graphics.drawable.Drawable;
  10. import android.util.AttributeSet;
  11.  
  12. import java.util.Random;
  13.  
  14.  
  15. /**
  16.  * Created by MOHAMADPC on 18/09/2017.
  17.  */
  18.  
  19. public class autoSeekBar extends android.support.v7.widget.AppCompatSeekBar implements Runnable {
  20.     private static Random rnd = new Random();
  21.  
  22.     // speed parameters: time to wait after each step
  23.     private static int minTime = 150;
  24.     private static int maxTime = 400;
  25.  
  26.     // progress changes in one step
  27.     private static int step = 1;
  28.  
  29.     // auto or manual progress
  30.     private boolean isAuto;
  31.  
  32.     public autoSeekBar(Context context, AttributeSet attrs) {
  33.         super(context, attrs);
  34.  
  35.         this.setBackgroundColor(Color.rgb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
  36.         this.setProgressDrawable(getBackground());
  37.         this.setMax(20);
  38.         isAuto = false;
  39.  
  40.     }
  41.  
  42.  
  43.     public autoSeekBar(Context context, int imageId) {
  44.         this(context, null);
  45.         Drawable thumb = getContext().getDrawable(imageId);
  46.         Bitmap b = ((BitmapDrawable) thumb).getBitmap();
  47.         Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 50, 50, false);
  48.         thumb = new BitmapDrawable(getResources(), bitmapResized);
  49.         setThumb(thumb);
  50.     }
  51.  
  52.     public autoSeekBar(Context context) {
  53.         this(context, null);
  54.     }
  55.  
  56.  
  57.     public void autoStart() {
  58.         this.setProgress(0);
  59.         isAuto = true;
  60.         new Thread(this).start();
  61.     }
  62.  
  63.     @Override
  64.     public void run() {
  65.         while (isAuto) {
  66.             setProgress(Math.min(getProgress() + step, getMax()));
  67.  
  68.             if (getProgress() == getMax()) {
  69.                 isAuto = false;
  70.                 ((MainActivity) getContext()).horseFinished(this);
  71.             } else {
  72.                 try {
  73.                     Thread.sleep(minTime + rnd.nextInt(maxTime - minTime + 1));
  74.                 } catch (InterruptedException e) {
  75.                     e.printStackTrace();
  76.                 }
  77.             }
  78.         }
  79.     }
  80. }
  81.  
  82.  
  83. MainActivity.java
  84. -----------------
  85. package com.example.mohamadpc.horserace;
  86.  
  87. import android.content.ActivityNotFoundException;
  88. import android.content.Intent;
  89. import android.net.Uri;
  90. import android.os.Bundle;
  91. import android.speech.RecognizerIntent;
  92. import android.support.v7.app.AppCompatActivity;
  93. import android.util.Log;
  94. import android.view.View;
  95. import android.widget.LinearLayout;
  96. import android.widget.Toast;
  97.  
  98. import java.util.ArrayList;
  99. import java.util.Locale;
  100. import java.util.Vector;
  101.  
  102. public class MainActivity extends AppCompatActivity {
  103.     //codes for startActivityForResult
  104.     final int AUDIO_NUMBER_RESULT = 100;
  105.     final int AUDIO_RUN_RESULT = 101;
  106.     LinearLayout llBackGround;
  107.  
  108.     private int horsesCount = -1;
  109.     private autoSeekBar[] myHorses;
  110.     private boolean isRacing;
  111.  
  112.     Vector<autoSeekBar> arrivedHorses = new Vector<autoSeekBar>();
  113.  
  114.     @Override
  115.     protected void onCreate(Bundle savedInstanceState) {
  116.         super.onCreate(savedInstanceState);
  117.         setContentView(R.layout.activity_main);
  118.  
  119.  
  120.         setPointer();
  121.     }
  122.  
  123.     public void setPointer() {
  124.         llBackGround = (LinearLayout) findViewById(R.id.llyBackGround);
  125.         llBackGround.setOnClickListener(new View.OnClickListener() {
  126.             @Override
  127.             public void onClick(View view) {
  128.                 if (horsesCount == -1) {
  129.                     getNumberBySpeech();
  130.                 } else {
  131.                     if (!isRacing) {
  132.                         if (arrivedHorses.size() == horsesCount) {
  133.                             clearLayout();
  134.                         } else {
  135.                             getCommandBySpeech();
  136.                         }
  137.                     }
  138.                 }
  139.             }
  140.         });
  141.         isRacing = false;
  142.     }
  143.  
  144.     private void getNumberBySpeech() {
  145.         try {
  146.             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  147.             intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
  148.                     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  149.             intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
  150.                     getResources().getString(R.string.speech_prompt) + "\n" + getResources().getString(R.string.tracks_number_prompt));
  151.             startActivityForResult(intent, AUDIO_NUMBER_RESULT);
  152.  
  153.         } catch (ActivityNotFoundException e) {
  154.             String appPackageName = "com.google.android.googlequicksearchbox";
  155.             try {
  156.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
  157.             } catch (ActivityNotFoundException ee) {
  158.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
  159.             }
  160.             Toast.makeText(this, "No such activity", Toast.LENGTH_SHORT).show();
  161.         }
  162.     }
  163.  
  164.     private void getCommandBySpeech() {
  165.         try {
  166.             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  167.             intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
  168.                     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  169.             intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
  170.                     getResources().getString(R.string.speech_prompt) + "\n" + getResources().getString(R.string.run_command_prompt));
  171.             startActivityForResult(intent, AUDIO_RUN_RESULT);
  172.  
  173.         } catch (ActivityNotFoundException e) {
  174.             String appPackageName = "com.google.android.googlequicksearchbox";
  175.             try {
  176.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
  177.             } catch (ActivityNotFoundException ee) {
  178.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
  179.             }
  180.             Toast.makeText(this, "No such activity", Toast.LENGTH_SHORT).show();
  181.         }
  182.     }
  183.  
  184.     @Override
  185.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  186.         if (resultCode == RESULT_OK) {
  187.             String strRes = "";
  188.             Bundle bundle = data.getExtras();
  189.             final ArrayList<String> matches = bundle.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
  190.  
  191.             switch (requestCode) {
  192.  
  193.                 case AUDIO_NUMBER_RESULT:
  194.                     for (String item : matches) {
  195.                         try {
  196.                             Log.d("Speech_Number", item);
  197.                             this.horsesCount = Integer.parseInt(item);
  198.                             break;
  199.                         } catch (Exception e) {
  200.                         }
  201.                     }
  202.                     if (this.horsesCount > 0) {
  203.                         setLayout();
  204.                     }
  205.                     break;
  206.  
  207.                 case AUDIO_RUN_RESULT:
  208.                     for (String item : matches) {
  209.                         Log.d("Speech_Number", item);
  210.                         if (item.toUpperCase().equals(getResources().getString(R.string.run_command_string).toUpperCase())) {
  211.                             startRace();
  212.                         }
  213.                     }
  214.                     break;
  215.             }
  216.         }
  217.     }
  218.  
  219.     private void startRace() {
  220.         arrivedHorses.clear();
  221.         for (int i = 0; i < myHorses.length; i += 1) {
  222.             myHorses[i].autoStart();
  223.         }
  224.         isRacing = true;
  225.     }
  226.  
  227.     private void setLayout() {
  228.         myHorses = new autoSeekBar[horsesCount];
  229.  
  230.         for (int i = 0; i < myHorses.length; i += 1) {
  231.             myHorses[i] = newHorse();
  232.             llBackGround.addView(myHorses[i]);
  233.         }
  234.         isRacing = false;
  235.     }
  236.  
  237.     private void clearLayout() {
  238.         arrivedHorses.clear();
  239.  
  240.         for (int i = 0; i < myHorses.length; i += 1) {
  241.             llBackGround.removeView(myHorses[i]);
  242.             myHorses[i] = null;
  243.         }
  244.  
  245.         myHorses = null;
  246.         horsesCount = -1;
  247.         isRacing = false;
  248.  
  249.     }
  250.  
  251.     private autoSeekBar newHorse() {
  252.         autoSeekBar newHorse;
  253.         if (isRTL()) {
  254.             newHorse = new autoSeekBar(this, R.drawable.rtl_horse);
  255.         } else {
  256.             newHorse = new autoSeekBar(this, R.drawable.ltr_horse);
  257.         }
  258.         LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
  259.         params.setMargins(0, 10, 0, 0);
  260.         newHorse.setLayoutParams(params);
  261.  
  262.         return newHorse;
  263.     }
  264.  
  265.     public void horseFinished(autoSeekBar horse) {
  266.         arrivedHorses.add(horse);
  267.         if (arrivedHorses.size() == horsesCount) {
  268.             double step = (double) myHorses[0].getMax() / myHorses.length;
  269.  
  270.             for (int i = 0; i < arrivedHorses.size(); i += 1) {
  271.                 arrivedHorses.get(i).setProgress((int) ((arrivedHorses.size() - i) * step));
  272.             }
  273.             isRacing = false;
  274.         }
  275.     }
  276.  
  277.     private boolean isRTL() {
  278.         return isRTL(Locale.getDefault());
  279.     }
  280.  
  281.     private boolean isRTL(Locale locale) {
  282.         final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0));
  283.         return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
  284.                 directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
  285.     }
  286. }
  287.  
  288.  
  289. strings.xml
  290. -----------
  291. <resources>
  292.     <string name="app_name">HorseRace</string>
  293.     <string name="speech_prompt">waiting for your words!</string>
  294.     <string name="tracks_number_prompt">Say Number of horses to race</string>
  295.     <string name="run_command_prompt">Say Run to start</string>
  296.     <string name="run_command_string">go</string>
  297. </resources>
  298.  
  299.  
  300. AndroidManifest.xml
  301. -------------------
  302. <?xml version="1.0" encoding="utf-8"?>
  303. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  304.     package="com.example.mohamadpc.horserace">
  305.  
  306.     <uses-permission android:name="android.permission.INTERNET" />
  307.     <uses-permission android:name="android.permission.RECORD_AUDIO" />
  308.     <uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
  309.  
  310.     <application
  311.         android:allowBackup="true"
  312.         android:icon="@mipmap/ic_launcher"
  313.         android:label="@string/app_name"
  314.         android:roundIcon="@mipmap/ic_launcher_round"
  315.         android:supportsRtl="true"
  316.         android:theme="@style/AppTheme">
  317.         <activity android:name=".MainActivity">
  318.             <intent-filter>
  319.                 <action android:name="android.intent.action.MAIN" />
  320.  
  321.                 <category android:name="android.intent.category.LAUNCHER" />
  322.             </intent-filter>
  323.         </activity>
  324.     </application>
  325. </manifest>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement