Back to project page Android-Apps.
The source code is released under:
Apache License
If you think the Android project Android-Apps listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.kniezrec.voiceremotefree; /*w w w. j a v a 2 s .c o m*/ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import com.google.ads.AdRequest; import com.google.ads.AdSize; import com.google.ads.AdView; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Vibrator; import android.preference.PreferenceManager; import android.speech.RecognizerIntent; import android.text.InputType; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Button; import android.widget.EditText; import android.widget.GridLayout; import android.widget.LinearLayout; import android.widget.Toast; public class MainActivity extends Activity { public static final int VOICE_RECOGNITION_REQUEST_CODE = 1001; public static final String PREFS_SERVER_HOST_KEY = "serverHost"; public static final String PREFS_TIMEOUT = "5"; public static final String PREFS_SERVER_HOST_DEFAULT = "Please change the IP address in settings"; public static final String PREFS_SERVER_PORT_KEY = "serverPort"; public static final String PREFS_SERVER_PORT_DEFAULT = "2345"; public static final String PREFS_SENDER_FACTORY_KEY = "keyCodeSenderFactory"; public static final String PREFS_LANGUAGE = "LanguageSet"; public static final String PREFS_TIMEOUT_KEY = "timeoutSec"; public static final String PREFS_PAUSE_KEY = "pauseSec"; public static final String PREFS_FAVOURITES = "favr"; public static final String PREFS_TO_LOUD_KEY = "toLoudKeys"; public static final String PREFS_TO_QUIET_KEY = "toQuietKey"; public static final String PREFS_SENDER_FACTORY_DEFAULT = CSeriesKeyCodeSenderFactory.class .getCanonicalName(); private AdView adView; private Button mbtSpeak; private Button refreshBut; private Commands cmds = null; private SharedPreferences prefs; private Sender mSender; private Handler mHandler = new Handler(); private boolean initialized; private static ScheduledExecutorService scheduler; private Thread initializer; private ArrayList<String> textMatchList = null; private boolean down = false; private GridLayout pad; private Set<String> actions; private Toast toa1; private Toast toa2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); adView = new AdView(MainActivity.this, AdSize.BANNER, "a150fe909848614"); adView.loadAd(new AdRequest()); setContentView(R.layout.activity_main); mbtSpeak = (Button) findViewById(R.id.speak); refreshBut = (Button) findViewById(R.id.refresh); pad = (GridLayout) findViewById(R.id.pad); actions = new HashSet<String>(); for (RemoteButton button : Commands.BUTTONS) { View v = findViewById(button.resId); if (v != null) { final int[] codes = button.keyCodes; v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { vibrate(MainActivity.this, 15); Integer[] codes1 = intArrayToIntegerArray(codes); SendKeysTask sendCodesTask = new SendKeysTask(); sendCodesTask.execute(codes1); } }); } } Button stop = (Button) findViewById(R.id.stop); stop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { vibrate(MainActivity.this, 15); stopScheduler(); } }); if (savedInstanceState != null) { boolean isD = savedInstanceState.getBoolean("downPad", false); if (isD) { translate(true); } } checkVoiceRecognition(); } @Override public void onDestroy() { if (adView != null) { adView.destroy(); } super.onDestroy(); } private void checkVoiceRecognition() { // Check if voice recognition is present PackageManager pm = getPackageManager(); boolean notLoaded = false; List<ResolveInfo> activities = pm.queryIntentActivities(new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); WifiManager wifiManager = (WifiManager) getApplicationContext() .getSystemService(Context.WIFI_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(this); if (!wifiManager.isWifiEnabled() || wifiManager.getConnectionInfo().getIpAddress() == 0) { toa1 = Toast.makeText(getApplicationContext(), R.string.enable_wifi, Toast.LENGTH_LONG); toa1.show(); mbtSpeak.setBackgroundResource(R.drawable.fail); notLoaded = true; refreshBut.setVisibility(View.VISIBLE); } if (activities.size() == 0 || notLoaded) { mbtSpeak.setEnabled(false); mbtSpeak.setBackgroundResource(R.drawable.fail); if (!notLoaded) { Toast.makeText(this, getResources().getString(R.string.voiceNotPresent), Toast.LENGTH_LONG).show(); } } else { if (initializer != null) { initializer.interrupt(); initializer = null; } if (!mbtSpeak.isEnabled()) { mbtSpeak.setEnabled(true); mbtSpeak.setBackgroundResource(R.drawable.ok); } refreshBut.setVisibility(View.GONE); cmds = new Commands(getApplicationContext()); initializer = new Thread(new Runnable() { public void run() { Looper.prepare(); cmds.loadResources(); initPrefs(); } }); initializer.start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection Intent intent = null; switch (item.getItemId()) { case R.id.menu_settings: intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; case R.id.help: intent = new Intent(this, HelpActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onStop() { super.onStop(); stopScheduler(); if (initializer != null) { initializer.interrupt(); initializer = null; } if (toa1 != null) toa1.cancel(); if (toa2 != null) toa2.cancel(); } private void stopScheduler() { if (scheduler != null && !scheduler.isShutdown()) { scheduler.shutdown(); scheduler = null; showToastMessage(getResources().getString(R.string.endShow)); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER); } } private static Integer[] intArrayToIntegerArray(int[] codes) { Integer[] result = new Integer[codes.length]; for (int i = 0; i < codes.length; i++) { result[i] = codes[i]; } return result; } public void expand(View view) { vibrate(MainActivity.this, 15); if (down) { translate(false); } else { translate(true); } } public void refresh(View view) { checkVoiceRecognition(); } public void actionsList(View view) { vibrate(MainActivity.this, 15); Intent intent = new Intent(this, ListActionsActivity.class); startActivity(intent); this.overridePendingTransition(R.anim.slide_x, R.anim.slidebackx); } public void startSpeak(View view) { try { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass() .getPackage().getName()); intent.putExtra(RecognizerIntent.EXTRA_SECURE, true); String pref = prefs.getString(MainActivity.PREFS_LANGUAGE, "default"); if (pref.equals("english")) { intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US"); } startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); actions = prefs.getStringSet(NewAction.PREFS_ACTIONS, actions); } catch (ActivityNotFoundException a) { Toast.makeText(this, getResources().getString(R.string.voiceNotPresent), Toast.LENGTH_LONG).show(); } } private void animateHigh(int or) { if (or == Configuration.ORIENTATION_PORTRAIT) { mbtSpeak.animate().setDuration(270).translationY(160); } else { mbtSpeak.animate().setDuration(270).translationX(200); } } private void animateXHigh(int or) { if (or == Configuration.ORIENTATION_PORTRAIT) { mbtSpeak.animate().setDuration(270).translationY(260); } else { mbtSpeak.animate().setDuration(270).translationX(230); } } private void animateSmall(int or) { if (or == Configuration.ORIENTATION_PORTRAIT) { mbtSpeak.animate().setDuration(270).translationY(100); } else { mbtSpeak.animate().setDuration(270).translationX(60); } } private void animateMedium(int or) { if (or == Configuration.ORIENTATION_PORTRAIT) { mbtSpeak.animate().setDuration(270).translationY(90); } else { mbtSpeak.animate().setDuration(270).translationX(100); } } private void translate(boolean upToDown) { Animation alphaAnim = null; Button expand = (Button) findViewById(R.id.expand); int or = getResources().getConfiguration().orientation; if (upToDown && !down) { alphaAnim = new AlphaAnimation(0.0f, 1.0f); down = true; pad.bringToFront(); setAllEnabled(true); expand.animate().setDuration(150).alpha(0.6f); float dpi = getResources().getDisplayMetrics().density; // 0.75 - ldpi // 1.0 - mdpi // 1.5 - hdpi // 2.0 - xhdpi // 3.0 - xxdpi if (dpi <= 0.75f) { animateSmall(or); } else if (dpi <= 1.0f) { animateMedium(or); } else if (dpi <= 1.5f) { animateHigh(or); } else if (dpi >= 2.0f) { animateXHigh(or); } } else if (!upToDown && down) { alphaAnim = new AlphaAnimation(1.0f, 0.0f); expand.animate().setDuration(150).alpha(1.0f); down = false; mbtSpeak.bringToFront(); setAllEnabled(false); if (or == Configuration.ORIENTATION_PORTRAIT) { mbtSpeak.animate().setDuration(270).translationY(0); } else { mbtSpeak.animate().setDuration(270).translationX(0); } } if (alphaAnim != null) { alphaAnim.setDuration(350); alphaAnim.setFillAfter(true); pad.startAnimation(alphaAnim); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("downPad", down); } private void setAllEnabled(boolean enabled) { for (int i = 0; i < pad.getChildCount(); i++) { Button b = (Button) pad.getChildAt(i); b.setEnabled(enabled); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) if (resultCode == RESULT_OK) { textMatchList = null; textMatchList = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (!textMatchList.isEmpty()) { Integer[] result = Mapper.mapResult(textMatchList, cmds, prefs); Integer[][] stps; if (result != null) { executeChannel(result); } else if ((stps = Mapper.checkActions(actions, textMatchList, prefs)) != null) { runAction(stps); } else { showDialog(textMatchList.get(0)); } } } else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) { showToastMessage(getResources().getString(R.string.AudioError)); } else if (resultCode == RecognizerIntent.RESULT_CLIENT_ERROR) { showToastMessage(getResources().getString(R.string.ClientError)); } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) { showToastMessage(getResources() .getString(R.string.NetworkError)); } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) { showToastMessage(getResources().getString(R.string.NoMatch)); } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) { showToastMessage(getResources().getString(R.string.ServerError)); } super.onActivityResult(requestCode, resultCode, data); } private boolean checkTimeout(Integer i) { Integer[] VALUES = new Integer[] { 4, 5, 6, 8, 9, 10, 12, 13, 14, 17, 16, 18, -1 }; return Arrays.asList(VALUES).contains(i); } private void runAction(final Integer[][] stps) { stopScheduler(); int currentOrientation = this.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } int time = Integer.parseInt(prefs.getString(PREFS_PAUSE_KEY, PREFS_TIMEOUT)); if (time < 4) time = 4; final int _tim = time; new Thread(new Runnable() { public void run() { for (Integer[] i : stps) { if (checkTimeout(i[0])) { executeChannel(i); try { Thread.sleep(_tim * 1000); } catch (InterruptedException e) { showToastMessage(e.getMessage()); } } else { try { Thread.sleep(800); } catch (InterruptedException e) { showToastMessage(e.getMessage()); } executeChannel(i); } } MainActivity.this .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER); } }).start(); } private boolean addToSharedPref(String command, int code) { boolean ret = false; if (!prefs.contains(command)) { SharedPreferences.Editor edit = prefs.edit(); edit.putInt(command, code); ret = edit.commit(); } return ret; } private boolean addToSharedPref(String command, String channel) { boolean ret = false; if (!prefs.contains(command)) { SharedPreferences.Editor edit = prefs.edit(); edit.putString(command, channel); ret = edit.commit(); } return ret; } private void executeChannel(Integer... codes) { SendKeysTask sendCodesTask = new SendKeysTask(); sendCodesTask.execute(codes); } private void showCustomDialog(String command) { final EditText text = new EditText(this); text.setInputType(InputType.TYPE_CLASS_NUMBER); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); text.setLayoutParams(lp); final String _command = new String(command); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(text); // Add the buttons builder.setPositiveButton(R.string.addSave, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); if (addToSharedPref(_command, text.getText().toString() + "_")) { showToastMessage(getResources().getString( R.string.save)); } else { showToastMessage(getResources().getString( R.string.notSave)); } } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.setTitle(R.string.channelLabel); AlertDialog dialog = builder.create(); dialog.show(); } private void addToResources(String string) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.addCommand); final String _command = new String(string); builder.setItems(R.array.buttons, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean val = false; boolean show = true; if (which == 0) { showCustomDialog(_command); show = false; dialog.cancel(); } else { int _tmp = Mapper.mapOptionToAction(Integer .toString(which)); val = addToSharedPref(_command, _tmp); } if (show) { if (val) { showToastMessage(getResources().getString( R.string.save)); } else { showToastMessage(getResources().getString( R.string.notSave)); } } } }); AlertDialog dialog = builder.create(); dialog.show(); } private void initPrefs() { SharedPreferences.Editor edit = prefs.edit(); boolean changes = false; if (!prefs.contains(PREFS_SERVER_HOST_KEY)) { edit.putString(PREFS_SERVER_HOST_KEY, PREFS_SERVER_HOST_DEFAULT); changes = true; } if (!prefs.contains(PREFS_SERVER_PORT_KEY) || prefs.getString(PREFS_SERVER_PORT_KEY, "").trim().equals("")) { edit.putString(PREFS_SERVER_PORT_KEY, PREFS_SERVER_PORT_DEFAULT); changes = true; } if (changes) { edit.commit(); } if (prefs.getString(PREFS_SERVER_HOST_KEY, PREFS_SERVER_HOST_DEFAULT) .equals(PREFS_SERVER_HOST_DEFAULT)) { Discovery discovery = new Discovery() { protected void onPostExecute(InetAddress addr) { if (addr != null) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return initializeConnection(); } protected void onPostExecute(Boolean result) { MainActivity.this.initialized = result; }; }.execute(); } }; }; discovery.execute(); } } @Override protected void onResume() { super.onResume(); WifiManager wifiManager = (WifiManager) getApplicationContext() .getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { mbtSpeak.setBackgroundResource(R.drawable.ok); mbtSpeak.setEnabled(true); checkVoiceRecognition(); } else { mbtSpeak.setBackgroundResource(R.drawable.fail); mbtSpeak.setEnabled(false); refreshBut.setVisibility(View.VISIBLE); } // Initialize the connection asynchronous new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return initializeConnection(); } protected void onPostExecute(Boolean result) { MainActivity.this.initialized = result; }; }.execute(); } private boolean initializeConnection() { if (mSender != null) mSender.uninitialize(); mSender = null; mSender = SenderFactory.createKeyCodeSender(this, prefs); try { mSender.initialize(); } catch (final IOException e) { mHandler.post(new Runnable() { public void run() { toa2 = Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG); toa2.show(); mbtSpeak.setBackgroundResource(R.drawable.fail); mbtSpeak.setEnabled(false); refreshBut.setVisibility(View.VISIBLE); } }); return false; } return true; } private void showDialog(String string) { final String _str = new String(string); AlertDialog.Builder builder = new AlertDialog.Builder(this); // Add the buttons builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); addToResources(_str); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.setTitle(getResources().getString(R.string.notfound) + " " + string); builder.setMessage(getResources().getString(R.string.wouldYoulike)); AlertDialog dialog = builder.create(); dialog.show(); } void showToastMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } private static int[] integerArrayToIntArray(Integer[] codes) { int[] result = new int[codes.length]; for (int i = 0; i < codes.length; i++) { result[i] = codes[i]; } return result; } private class SendKeysTask extends AsyncTask<Integer, Void, Void> { @Override protected Void doInBackground(Integer... codes) { try { if (mSender == null) return null; if (!MainActivity.this.initialized) MainActivity.this.mSender.initialize(); if (mSender instanceof KeyCodeSender) { KeyCodeSender keyCodeSender = (KeyCodeSender) mSender; keyCodeSender.sendCode(integerArrayToIntArray(codes)); if (codes[codes.length - 1] == Commands.BTN_POWER_OFF) { finish(); } } } catch (InterruptedException e) { } catch (final UnknownHostException e) { mHandler.post(new Runnable() { public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); mbtSpeak.setBackgroundResource(R.drawable.fail); mbtSpeak.setEnabled(false); refreshBut.setVisibility(View.VISIBLE); } }); } catch (final IOException e) { mHandler.post(new Runnable() { public void run() { mbtSpeak.setBackgroundResource(R.drawable.fail); mbtSpeak.setEnabled(false); refreshBut.setVisibility(View.VISIBLE); } }); } return null; } } public static void vibrate(Context context, long millis) { if (millis == 0) return; Vibrator v = (Vibrator) context .getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(millis); } } }