Android Open Source - Android-Apps Main Fragment






From Project

Back to project page Android-Apps.

License

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.

Java Source Code

package com.kniezrec.voiceremote2;
/*from   www.  j a va  2 s .  co 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.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

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.content.res.Resources;
import android.graphics.Typeface;
import android.media.AudioManager;
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.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainFragment extends Fragment implements ViewSwitcher.ViewFactory {
  private TextSwitcher mSwitcher = null;
  private Button mbtSpeak = null;
  private Commands cmds = null;
  private SharedPreferences prefs = null;
  private Sender mSender;
  private Handler mHandler = new Handler();
  private boolean initialized;
  private static ScheduledExecutorService scheduler = null;
  private Thread initializer = null;
  private ArrayList<String> textMatchList = null;
  private Set<String> actions = null;
  private Toast toa1 = null;
  private Toast toa2 = null;
  private MainActivity mAct = null;
  private View fragView = null;
  private Timer timer = null;
  private TimerTask task = null;
  private Button btn_prefs = null;
  private SpeechRecognizer sr = null;
  public boolean isListening;
  private static final String TAG = "VoiceRemoteMainFrag";
  private AudioManager audioManager = null;
  private int LAST_STATE;
  private Context appCtx = null;
  private Resources res = null;
  private Button refreshBtn = null;
  public AdView adView;

  //private static final String TEST_DEVICE_ID = "samsung-gt_i9300-4df1f25b616b5f6b";

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    mAct = (MainActivity) activity;
    res = mAct.getResources();
    appCtx = mAct.getApplicationContext();
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    isListening = false;
    timer = new Timer();
    sr = SpeechRecognizer.createSpeechRecognizer(appCtx);
    sr.setRecognitionListener(new VoiceListener());
    audioManager = (AudioManager) mAct
        .getSystemService(Context.AUDIO_SERVICE);
    LAST_STATE = 0;
    setRetainInstance(true);
  };

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    fragView = inflater.inflate(R.layout.activity_main, null);

    adView = (AdView) fragView.findViewById(R.id.adView);
    btn_prefs = (Button) fragView.findViewById(R.id.btn_prefs);
    btn_prefs.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(appCtx, SettingsActivity.class);
        startActivity(intent);
        mAct.overridePendingTransition(R.anim.slide_x,
            R.anim.slidebackx);
      }
    });

    mSwitcher = (TextSwitcher) fragView.findViewById(R.id.statusText);
    mSwitcher.setFactory(this);

    Animation in = AnimationUtils.loadAnimation(appCtx, R.anim.push_up_in);
    Animation out = AnimationUtils
        .loadAnimation(appCtx, R.anim.push_up_out);
    mSwitcher.setInAnimation(in);
    mSwitcher.setOutAnimation(out);

    mbtSpeak = (Button) fragView.findViewById(R.id.speak);
    mbtSpeak.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        startSpeak();
      }
    });

    final Button stop = (Button) fragView.findViewById(R.id.stop);
    stop.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        vibrate(appCtx, 15);
        stopScheduler();
      }
    });

    refreshBtn = (Button) fragView.findViewById(R.id.refresh);
    refreshBtn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        refresh(fragView);
      }
    });

    return fragView;
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    for (RemoteButton button : Commands.BUTTONS) {
      View v = fragView.findViewById(button.resId);
      if (v != null) {
        final int[] codes = button.keyCodes;
        v.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
            vibrate(appCtx, 15);
            Integer[] codes1 = intArrayToIntegerArray(codes);
            SendKeysTask sendCodesTask = new SendKeysTask();
            sendCodesTask.execute(codes1);
          }
        });
      }
    }
    AdRequest adRequest = new AdRequest.Builder().build();
    // .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
    // .addTestDevice(TEST_DEVICE_ID).build();
    adView.loadAd(adRequest);
  }

  class VoiceListener implements RecognitionListener {
    public void onReadyForSpeech(Bundle params) {
      mSwitcher.setText(res.getString(R.string.listen));
      mbtSpeak.setBackgroundResource(R.drawable.speaking);
    }

    public void onBeginningOfSpeech() {
    }

    public void onRmsChanged(float rmsdB) {
    }

    public void onBufferReceived(byte[] buffer) {
    }

    public void onEndOfSpeech() {
      audioManager.setSpeakerphoneOn(false);
    }

    public void onError(int error) {
      switch (error) {
      case SpeechRecognizer.ERROR_AUDIO:
        showToastMessage(res.getString(R.string.AudioError));
        break;
      case SpeechRecognizer.ERROR_CLIENT:
        showToastMessage(res.getString(R.string.ClientError));
        break;
      case SpeechRecognizer.ERROR_NETWORK:
        showToastMessage(res.getString(R.string.NetworkError));
        break;
      case SpeechRecognizer.ERROR_NO_MATCH:
        showToastMessage(res.getString(R.string.NoMatch));
        break;
      case SpeechRecognizer.ERROR_SERVER:
        showToastMessage(res.getString(R.string.ServerError));
        break;

      default:
        break;
      }
      isListening = false;
      mSwitcher.setText(res.getString(LAST_STATE));
      mbtSpeak.setBackgroundResource(R.drawable.ok);
    }

    public void onResults(Bundle results) {
      mbtSpeak.setBackgroundResource(R.drawable.ok);
      isListening = false;
      textMatchList = null;
      textMatchList = results
          .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

      if (!textMatchList.isEmpty()) {
        String statusT = null;
        for (String a : textMatchList) {
          if (a.isEmpty()) {
            continue;
          }
          statusT = a;
          break;
        }

        int id = Mapper.checkSpecialInstruction(textMatchList, cmds,
            prefs);
        if (id != Commands.NOT_FOUND) {
          ChangeStatusText(statusT);
          startAction(id);
        } else {
          Integer[] result = Mapper.mapResult(statusT, cmds, prefs);
          Integer[][] stps;
          if (result != null) {
            try {
              Integer.parseInt(statusT);
              ChangeStatusText(res.getString(R.string.channel)
                  + statusT);
            } catch (NumberFormatException e) {
              ChangeStatusText(statusT);
            }

            executeChannel(result);
          } else if ((stps = Mapper.checkActions(actions, statusT,
              prefs)) != null) {
            ChangeStatusText(statusT);
            runAction(stps);
          } else {
            ChangeStatusText(statusT);
            showDialog(statusT);
          }
        }
      }
    }

    public void onPartialResults(Bundle partialResults) {
      Log.d(TAG, "onPartialResults");
    }

    public void onEvent(int eventType, Bundle params) {
      Log.d(TAG, "onEvent " + eventType);
    }
  }

  private void checkVoiceRecognition() {
    Log.v("", "CHECK");
    // Check if voice recognition is present
    PackageManager pm = mAct.getPackageManager();
    boolean notLoaded = false;
    List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
        RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    WifiManager wifiManager = (WifiManager) appCtx
        .getSystemService(Context.WIFI_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(mAct);

    if (!wifiManager.isWifiEnabled()
        || wifiManager.getConnectionInfo().getIpAddress() == 0) {
      toa1 = Toast.makeText(appCtx, R.string.enable_wifi,
          Toast.LENGTH_LONG);
      toa1.show();
      LAST_STATE = R.string.disconnect;
      mSwitcher.setText(res.getString(LAST_STATE));
      // mbtSpeak.setBackgroundResource(R.drawable.fail);
      notLoaded = true;
      refreshBtn.setVisibility(View.VISIBLE);
    }
    if (activities.size() == 0 || notLoaded) {
      mbtSpeak.setEnabled(false);
      // mbtSpeak.setBackgroundResource(R.drawable.fail);
      LAST_STATE = R.string.disconnect;
      mSwitcher.setText(res.getString(LAST_STATE));
      if (!notLoaded) {
        Toast.makeText(appCtx, res.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);
      LAST_STATE = R.string.connected;
      mSwitcher.setText(res.getString(LAST_STATE));
      // }
      refreshBtn.setVisibility(View.INVISIBLE);
      cmds = new Commands(appCtx);
      initializer = new Thread(new Runnable() {
        public void run() {
          Looper.prepare();
          cmds.loadResources();
          initPrefs();
          cmds.loadFavourities(prefs.getString(
              MainActivity.PREFS_FAVOURITES, ""));
        }
      });
      initializer.start();

      // Initialize the connection asynchronous
      new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... params) {
          return initializeConnection();
        }

        protected void onPostExecute(Boolean result) {
          MainFragment.this.initialized = result;
        };

      }.execute();
    }
  }

  private void ResetTimer() {
    if (task != null)
      task.cancel();
    task = new TimerTask() {
      @Override
      public void run() {
        mAct.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            String txt = res.getString(LAST_STATE);
            mSwitcher.setText(txt);
          }
        });
      }
    };
    timer.schedule(task, 4 * 1000);
  }

  @Override
  public 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(res.getString(R.string.endShow));
      mAct.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 refresh(View view) {
    checkVoiceRecognition();
  }

  public void actionsList(View view) {
    vibrate(appCtx, 15);
    Intent intent = new Intent(mAct, ListActionsFragment.class);
    startActivity(intent);
    mAct.overridePendingTransition(R.anim.slide_x, R.anim.slidebackx);
  }

  public void startSpeak() {
    if (!isListening) {
      isListening = true;
      try {
        audioManager.setSpeakerphoneOn(true);
        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");
        }
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
        sr.startListening(intent);
        if (task != null)
          task.cancel();
        actions = prefs.getStringSet(NewAction.PREFS_ACTIONS, actions);
        if (actions == null) {
          actions = new HashSet<String>();
        }
      } catch (ActivityNotFoundException a) {
        Toast.makeText(appCtx, res.getString(R.string.voiceNotPresent),
            Toast.LENGTH_LONG).show();
      }
    } else {
      StopListening();
    }
  }

  public void StopListening() {
    isListening = false;
    sr.stopListening();
    sr.cancel();
    mSwitcher.setText(res.getString(LAST_STATE));
    mbtSpeak.setBackgroundResource(R.drawable.ok);
  }

  private void ChangeStatusText(String text) {
    StringBuilder sb = new StringBuilder();
    sb.append("\"" + text + "\"");
    mSwitcher.setText(sb.toString());
    ResetTimer();
  }

  private boolean checkTimeout(Integer i) {
    final 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.res.getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
      mAct.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    } else {
      mAct.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }
    int time = Integer.parseInt(prefs.getString(
        MainActivity.PREFS_PAUSE_KEY, MainActivity.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(2000);
            } catch (InterruptedException e) {
              showToastMessage(e.getMessage());
            }
            executeChannel(i);
          }

        }
        mAct.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 startAction(int reqId) {
    int currentOrientation = this.res.getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
      mAct.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    } else {
      mAct.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }
    switch (reqId) {
    case Commands.SHOW_ALL: {
      stopScheduler();
      scheduler = Executors.newScheduledThreadPool(1);
      int time = Integer
          .parseInt(prefs.getString(MainActivity.PREFS_TIMEOUT_KEY,
              MainActivity.PREFS_TIMEOUT));
      Runnable pinger = new Runnable() {
        public void run() {
          executeChannel(Integer.valueOf(Commands.BTN_CHANNEL_UP));
        }
      };
      scheduler.scheduleAtFixedRate(pinger, 0, time, TimeUnit.SECONDS);

    }
      break;

    case Commands.SHOW_ALL_BACK: {
      stopScheduler();
      scheduler = Executors.newScheduledThreadPool(1);
      int time = Integer
          .parseInt(prefs.getString(MainActivity.PREFS_TIMEOUT_KEY,
              MainActivity.PREFS_TIMEOUT));
      Runnable pinger = new Runnable() {
        public void run() {
          executeChannel(Integer.valueOf(Commands.BTN_CHANNEL_DOWN));
        }
      };
      scheduler.scheduleAtFixedRate(pinger, 0, time, TimeUnit.SECONDS);

    }
      break;

    case Commands.SHOW_ONLY_FAV: {
      if (cmds.favouriteList != null && !cmds.favouriteList.isEmpty()) {
        stopScheduler();
        scheduler = Executors.newScheduledThreadPool(1);
        int time = Integer.parseInt(prefs.getString(
            MainActivity.PREFS_TIMEOUT_KEY,
            MainActivity.PREFS_TIMEOUT));
        if (time < 4)
          time = 4;
        Runnable pinger = new Runnable() {
          String channel;
          int ind = 0;

          public void run() {
            channel = cmds.favouriteList.get(ind);
            executeChannel(channel);
            ind = (ind + 1) % (cmds.favouriteList.size());
          }
        };
        scheduler
            .scheduleAtFixedRate(pinger, 0, time, TimeUnit.SECONDS);
      } else {
        showToastMessage(res.getString(R.string.empty));
      }
    }
      break;
    case Commands.STOP: {
      stopScheduler();
    }
      break;

    case Commands.TO_LOUD: {
      int steps = Integer.parseInt(prefs.getString(
          MainActivity.PREFS_TO_LOUD_KEY, "4"));
      Integer[] _steps = new Integer[steps];
      Arrays.fill(_steps, Commands.BTN_VOLUME_DOWN);
      executeChannel(_steps);
    }
      break;

    case Commands.TO_QUIET: {
      int steps = Integer.parseInt(prefs.getString(
          MainActivity.PREFS_TO_QUIET_KEY, "4"));
      Integer[] _steps = new Integer[steps];
      Arrays.fill(_steps, Commands.BTN_VOLUME_UP);
      executeChannel(_steps);
    }
      break;

    case Commands.WRITE: {
      new Thread(new Runnable() {
        public void run() {
          TextSender sender = (TextSender) mSender;
          String txtToSend = textMatchList.get(0);
          String txt = textMatchList.get(textMatchList.size() - 1);
          try {
            sender.sendText(txtToSend.replaceFirst(txt, "").trim());
          } catch (IOException e) {
          } catch (InterruptedException e) {
          }
        }
      }).start();
    }

      break;
    default:
      break;
    }
  }

  private void executeChannel(Integer... codes) {
    SendKeysTask sendCodesTask = new SendKeysTask();
    sendCodesTask.execute(codes);
  }

  private void executeChannel(String channels) {
    SendKeysTask sendCodesTask = new SendKeysTask();
    sendCodesTask.execute(Mapper.parseNumber(channels));
  }

  private void showCustomDialog(String command) {
    final EditText text = new EditText(mAct);
    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(mAct);
    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(res.getString(R.string.save));
            } else {
              showToastMessage(res.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(mAct);
    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(res.getString(R.string.save));
                mAct.refreshList();
              } else {
                showToastMessage(res
                    .getString(R.string.notSave));
              }
            }
          }
        });
    AlertDialog dialog = builder.create();
    dialog.show();
  }

  private void initPrefs() {
    SharedPreferences.Editor edit = prefs.edit();
    boolean changes = false;
    if (!prefs.contains(MainActivity.PREFS_SERVER_HOST_KEY)) {
      edit.putString(MainActivity.PREFS_SERVER_HOST_KEY,
          MainActivity.PREFS_SERVER_HOST_DEFAULT);
      changes = true;
    }
    if (!prefs.contains(MainActivity.PREFS_SERVER_PORT_KEY)
        || prefs.getString(MainActivity.PREFS_SERVER_PORT_KEY, "")
            .trim().equals("")) {
      edit.putString(MainActivity.PREFS_SERVER_PORT_KEY,
          MainActivity.PREFS_SERVER_PORT_DEFAULT);
      changes = true;
    }
    if (changes) {
      edit.commit();
    }
    if (prefs.getString(MainActivity.PREFS_SERVER_HOST_KEY,
        MainActivity.PREFS_SERVER_HOST_DEFAULT).equals(
        MainActivity.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) {
                MainFragment.this.initialized = result;
              };

            }.execute();
          }
        };
      };
      discovery.execute();
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    if (cmds != null)
      cmds.loadFavourities(prefs.getString(MainActivity.PREFS_FAVOURITES,
          ""));
    if (isListening) {
      mbtSpeak.setBackgroundResource(R.drawable.speaking);
      mSwitcher.setText(res.getString(R.string.listen));
      if (!mbtSpeak.isEnabled()) {
        mbtSpeak.setEnabled(true);
      }
    } else {
      checkVoiceRecognition();
    }

  }

  private boolean initializeConnection() {
    if (mSender != null)
      mSender.uninitialize();
    mSender = null;
    mSender = SenderFactory.createKeyCodeSender(appCtx, prefs);
    try {
      mSender.initialize();
    } catch (final IOException e) {
      mHandler.post(new Runnable() {

        public void run() {
          toa2 = Toast.makeText(appCtx, e.getMessage(),
              Toast.LENGTH_LONG);
          toa2.show();
          // mbtSpeak.setBackgroundResource(R.drawable.fail);
          LAST_STATE = R.string.disconnect;
          mSwitcher.setText(res.getString(LAST_STATE));
          mbtSpeak.setEnabled(false);
          refreshBtn.setVisibility(View.VISIBLE);
        }
      });
      return false;
    }
    return true;
  }

  private void showDialog(String string) {
    final String _str = new String(string);
    AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
    // 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(res.getString(R.string.notfound) + " " + string);
    builder.setMessage(res.getString(R.string.wouldYoulike));
    AlertDialog dialog = builder.create();
    dialog.show();

  }

  void showToastMessage(String message) {
    Toast.makeText(appCtx, 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 (!MainFragment.this.initialized)
          MainFragment.this.mSender.initialize();
        if (mSender instanceof KeyCodeSender) {
          KeyCodeSender keyCodeSender = (KeyCodeSender) mSender;
          keyCodeSender.sendCode(integerArrayToIntArray(codes));
          if (codes[codes.length - 1] == Commands.BTN_POWER_OFF) {
            mAct.finish();
          }
        }
      } catch (InterruptedException e) {

      } catch (final UnknownHostException ex) {
        mHandler.post(new Runnable() {
          public void run() {
            Toast.makeText(appCtx, ex.getMessage(),
                Toast.LENGTH_LONG).show();
            // mbtSpeak.setBackgroundResource(R.drawable.fail);
            LAST_STATE = R.string.disconnect;
            mSwitcher.setText(res.getString(LAST_STATE));
            mbtSpeak.setEnabled(false);
            refreshBtn.setVisibility(View.INVISIBLE);
          }
        });
      } catch (final IOException e) {
        mHandler.post(new Runnable() {

          public void run() {
            // mbtSpeak.setBackgroundResource(R.drawable.fail);
            LAST_STATE = R.string.disconnect;
            mSwitcher.setText(res.getString(LAST_STATE));
            mbtSpeak.setEnabled(false);
            refreshBtn.setVisibility(View.INVISIBLE);
          }
        });
      }
      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);
    }
  }

  @Override
  public View makeView() {
    LayoutInflater inflater = LayoutInflater.from(mAct);
    TextView textView = (TextView) inflater
        .inflate(R.layout.textview, null);
    Typeface custom_font = Typeface.createFromAsset(mAct.getAssets(),
        "fonts/helvetica.ttf");
    textView.setTypeface(custom_font);
    return textView;
  }
}




Java Source Code List

com.kniezrec.remoterecorder.Communication.java
com.kniezrec.remoterecorder.MainServiceConnection.java
com.kniezrec.remoterecorder.MainService.java
com.kniezrec.remoterecorder.RequestType.java
com.kniezrec.remoterecorder.Request.java
com.kniezrec.voiceremote2.BSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremote2.BSeriesSender.java
com.kniezrec.voiceremote2.CSeriesButtons.java
com.kniezrec.voiceremote2.CSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremote2.CSeriesSender.java
com.kniezrec.voiceremote2.CommandsFragment.java
com.kniezrec.voiceremote2.Commands.java
com.kniezrec.voiceremote2.Discovery.java
com.kniezrec.voiceremote2.FSeriesButtons.java
com.kniezrec.voiceremote2.Group.java
com.kniezrec.voiceremote2.HelpFragment.java
com.kniezrec.voiceremote2.HostnamePreference.java
com.kniezrec.voiceremote2.KeyCodeSender.java
com.kniezrec.voiceremote2.ListActionsFragment.java
com.kniezrec.voiceremote2.MainActivity.java
com.kniezrec.voiceremote2.MainFragment.java
com.kniezrec.voiceremote2.Mapper.java
com.kniezrec.voiceremote2.MyExpandableListAdapter.java
com.kniezrec.voiceremote2.NewActionEdit.java
com.kniezrec.voiceremote2.NewActionSingleEdit.java
com.kniezrec.voiceremote2.NewAction.java
com.kniezrec.voiceremote2.RemoteButton.java
com.kniezrec.voiceremote2.SenderFactory.java
com.kniezrec.voiceremote2.Sender.java
com.kniezrec.voiceremote2.SettingsActivity.java
com.kniezrec.voiceremote2.TextSender.java
com.kniezrec.voiceremotefree.BSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremotefree.BSeriesSender.java
com.kniezrec.voiceremotefree.CSeriesButtons.java
com.kniezrec.voiceremotefree.CSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremotefree.CSeriesSender.java
com.kniezrec.voiceremotefree.Commands.java
com.kniezrec.voiceremotefree.Discovery.java
com.kniezrec.voiceremotefree.FSeriesButtons.java
com.kniezrec.voiceremotefree.HelpActivity.java
com.kniezrec.voiceremotefree.HostnamePreference.java
com.kniezrec.voiceremotefree.KeyCodeSender.java
com.kniezrec.voiceremotefree.ListActionsActivity.java
com.kniezrec.voiceremotefree.MainActivity.java
com.kniezrec.voiceremotefree.Mapper.java
com.kniezrec.voiceremotefree.NewActionEdit.java
com.kniezrec.voiceremotefree.NewActionSingleEdit.java
com.kniezrec.voiceremotefree.NewAction.java
com.kniezrec.voiceremotefree.RemoteButton.java
com.kniezrec.voiceremotefree.SenderFactory.java
com.kniezrec.voiceremotefree.Sender.java
com.kniezrec.voiceremotefree.Setings.java
com.kniezrec.voiceremotefree.SettingsActivity.java
com.kniezrec.voiceremotefree.TextSender.java
com.kniezrec.xbmcgear.connection.AndroidApplication.java
com.kniezrec.xbmcgear.connection.Connection.java
com.kniezrec.xbmcgear.connection.GearJSON.java
com.kniezrec.xbmcgear.connection.JSONRPCRequest.java
com.kniezrec.xbmcgear.connection.JSONRequestFactory.java
com.kniezrec.xbmcgear.connection.NSDResolve.java
com.kniezrec.xbmcgear.connection.NSDSearch.java
com.kniezrec.xbmcgear.connection.ProviderConnection.java
com.kniezrec.xbmcgear.connection.ProviderService.java
com.kniezrec.xbmcgear.connection.ResponseParser.java
com.kniezrec.xbmcgear.connection.WakeOnLan.java
com.kniezrec.xbmcgear.player.Kodi.java
com.kniezrec.xbmcgear.player.Player.java
com.kniezrec.xbmcgear.player.Playlist.java
com.kniezrec.xbmcgear.player.Song.java
com.kniezrec.xbmcgear.player.Video.java
com.kniezrec.xbmcgear.preferences.HostTable.java
com.kniezrec.xbmcgear.preferences.Host.java
com.kniezrec.xbmcgear.preferences.HostsDataSource.java
com.kniezrec.xbmcgear.preferences.HostsDatabaseHelper.java
com.kniezrec.xbmcgear.preferences.SharedPreferencesUtil.java
com.kniezrec.xbmcgear.presentation.AnimationManager.java
com.kniezrec.xbmcgear.presentation.AutoConfigurationActivity.java
com.kniezrec.xbmcgear.presentation.HostSetActivity.java
com.kniezrec.xbmcgear.presentation.InstanceActivity.java
com.kniezrec.xbmcgear.presentation.MainActivity.java
com.kniezrec.xbmcgear.presentation.StyleDialogFragment.java
com.kniezrec.xbmcgear.presentation.ViewMode.java
com.uraroji.garage.android.lame.SimpleLame.java
com.uraroji.garage.android.mp3recvoice.RecMicToMp3.java
de.quist.samy.remocon.Base64.java
de.quist.samy.remocon.Base64.java
de.quist.samy.remocon.ConnectionDeniedException.java
de.quist.samy.remocon.ConnectionDeniedException.java
de.quist.samy.remocon.Key.java
de.quist.samy.remocon.Key.java
de.quist.samy.remocon.Loggable.java
de.quist.samy.remocon.Loggable.java
de.quist.samy.remocon.RemoteReader.java
de.quist.samy.remocon.RemoteReader.java
de.quist.samy.remocon.RemoteSession.java
de.quist.samy.remocon.RemoteSession.java