package com.softwarefools.nik.spiritlevel; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.sql.Array; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.SharedPreferences; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.Vector; import android.graphics.Canvas; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Environment; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.provider.Settings; import android.speech.tts.Voice; import android.util.DisplayMetrics; // // //import com.softwarefools.nik.spiritlevel.R; //import com.softwarefools.nik.spiritlevel.R.layout; //import com.softwarefools.nik.spiritlevel.R.menu; import com.softwarefools.spiritlevel.R; import com.softwarefools.nik.spiritlevel.MySensorListener; import com.softwarefools.nik.spiritlevel.MySensorManager; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.annotation.TargetApi; import android.app.Activity; import android.content.pm.ActivityInfo; import android.speech.tts.TextToSpeech; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Surface; import android.view.View; import android.widget.TextView; import android.widget.Toast; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; //Toast.makeText(getBaseContext(), "Sometext", Toast.LENGTH_SHORT).show(); // Toast Vorlage public class LevelActivity extends Activity implements MySensorListener{ public static DecimalFormat f = new DecimalFormat("#0.000"); private static final String TAG = "SpiritLevel"; private int MY_DATA_CHECK_CODE = 0; //public static final String PREFS_NAME = "MyPrefsFile"; // private SensorManager mSensorManager; // private Sensor mySensor; //private Sensor aSensor,gSensor; private LevelView levelView; private AppPreferences myprefs; //private ArrayList accelvector; private Vector accelvector; private Vector gravvector; private Vector magvector; //private TextView accelField; //private TextView gravityField; private Random r; private Locale myLocale; SharedPreferences mySettings; private TextToSpeech myTTS; TextToSpeech t1; private int orientation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); levelView = new LevelView(this); myprefs = new AppPreferences(); Log.i(TAG,"LevelActivity.onCreate()"); setContentView(levelView); mySettings = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = mySettings.edit(); editor.putBoolean("applicationRecording", false); editor.commit(); r = new Random(); accelvector= new Vector<>(); gravvector = new Vector<>(); magvector = new Vector<>(); //TTS Engine Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE); myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS){ myTTS.setLanguage(getResources().getConfiguration().locale); funkSpeech(myTTS,false); }else if (status == TextToSpeech.ERROR) { Log.i(TAG,getApplicationContext().getString(R.string.action_lang_NA)); Toast.makeText(getBaseContext(), getApplicationContext().getString(R.string.action_lang_NA), Toast.LENGTH_LONG).show(); } } }); restartTTS(); setupActionBar(); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG,"onActivityResult() RequestCode"+requestCode+" resultCode"+resultCode); if (requestCode == MY_DATA_CHECK_CODE) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS){ funkSpeech(myTTS,false); myTTS.setLanguage(getResources().getConfiguration().locale); }else if (status == TextToSpeech.ERROR) { Toast.makeText(getBaseContext(), getApplicationContext().getString(R.string.action_lang_NA), Toast.LENGTH_LONG).show(); } } }); } else { Intent installTTSIntent = new Intent(); installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installTTSIntent); } } } @Override public void onResume() { super.onResume(); Log.i(TAG,"LevelActivity.onResume()"); restartTTS(); //Toast.makeText(getBaseContext(), "On Resume", Toast.LENGTH_SHORT).show(); // Toast Vorlage // Toast.makeText(getBaseContext(), "onResume Sensors Started", Toast.LENGTH_SHORT).show(); orientation=getScreenOrientation(); // orientation= getResources().getConfiguration().orientation; //Check device supported Accelerometer senssor or not if (MySensorManager.isSupported(this)) { //Start Accelerometer Listening MySensorManager.startListening(this); Log.i(TAG,"SensorManager-Start Listening"); } } @Override public void onStop() { super.onStop(); Log.i(TAG,"LevelActivity.onStop()"); // myTTS.stop(); //Check device supported Accelerometer senssor or not if (MySensorManager.isListening()) { //Start Accelerometer Listening MySensorManager.stopListening(); Log.i(TAG,"SensorManager-Stop Listening"); //Toast.makeText(getBaseContext(), "onStop Sensors Stoped",Toast.LENGTH_SHORT).show(); } } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG,"LevelActivity.onDestroy()"); //myTTS.shutdown(); //Check device supported Accelerometer senssor or not if (MySensorManager.isListening()) { //Start Accelerometer Listening MySensorManager.stopListening(); Log.i(TAG,"SensorManager-Stop Listening"); //Toast.makeText(getBaseContext(), "onDestroy Sensors Stoped", Toast.LENGTH_SHORT).show(); } } @Override public void onPause() { super.onPause(); Log.i(TAG,"LevelActivity.onPause()"); //myTTS.shutdown(); //Check device supported Accelerometer senssor or not if (MySensorManager.isListening()) { //Start Accelerometer Listening MySensorManager.stopListening(); Log.i(TAG,"SensorManager-Stop Listening"); //Toast.makeText(getBaseContext(), "onDestroy Sensors Stoped", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { //menu.clear(); // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.level, menu); Log.i(TAG,"LevelActivity.onCreateOptionsMenu()"); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); // Clear the menu first Log.i(TAG,"LevelActivity.onPrepareOptionsMenu()"); /* Add the menu items */ getMenuInflater().inflate(R.menu.level, menu); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getBoolean("applicationRecording",true)) { menu.removeItem(R.id.action_record); }else{ menu.removeItem(R.id.action_record_off); } //return super.onPrepareOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Handle item selection switch (item.getItemId()) { case R.id.action_settings: beLoud(this.getString(R.string.action_settings)); Log.i(TAG,"LevelActivity.onOptionsItemSelected() "+this.getString(R.string.action_settings)); //t1.speak(this.getString(R.string.action_settings), TextToSpeech.QUEUE_FLUSH, null); /*Intent refresh = new Intent(this, AppPreferences.class); startActivity(refresh);*/ if (MySensorManager.isListening()) { MySensorManager.stopListening(); } if (Build.VERSION.SDK_INT < 11) { startActivity(new Intent(this,AppPreferencesClassic.class)); Log.i(TAG,"Starting Oldschool Settings"); } else { startActivity(new Intent(this, AppPreferences.class)); Log.i(TAG,"Starting Settings"); } return true; case R.id.action_record: Log.i(TAG,"LevelActivity.onOptionsItemSelected() "+this.getString(R.string.action_record)); //System.out.println("Start Recording"); beLoud(this.getString(R.string.action_record_text)); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("applicationRecording",true); editor.commit(); return true; case R.id.action_record_off: //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Log.i(TAG,"LevelActivity.onOptionsItemSelected() "+this.getString(R.string.action_record_off)); //System.out.println("Stop Recording"); beLoud(this.getString(R.string.action_record_text_off)); SharedPreferences.Editor editor2 = prefs.edit(); editor2.putBoolean("applicationRecording",false); editor2.commit(); //Toast.makeText(getBaseContext(), "Vector:"+accelvector.size()+"\n"+printVect(accelvector), Toast.LENGTH_LONG).show(); // Save The DATA Log.d(TAG,"AccelerationVect Size:"+accelvector.size()); Log.d(TAG,"GravityVect Size:"+gravvector.size()); Log.d(TAG,"MagneticVect Size:"+magvector.size()); new ProcessData().execute(gravvector,accelvector,magvector); //new ProcessData().execute(accelvector); return true; case R.id.action_exit: //t1.speak(this.getString(R.string.goodby), TextToSpeech.QUEUE_FLUSH, null); Log.i(TAG,"LevelActivity.onOptionsItemSelected() "+this.getString(R.string.action_exit)); exitAll(); return true; case R.id.action_changelang: //t1.speak(this.getString(R.string.change_text), TextToSpeech.QUEUE_FLUSH, null); //System.out.println("Change Language"); Log.i(TAG,"LevelActivity.onOptionsItemSelected() "+this.getString(R.string.action_lang)); String[] sf=getResources().getStringArray(R.array.langValues); String comp=getResources().getConfiguration().locale.getLanguage(); String neus; do { int neur = r.nextInt(sf.length); neus = sf[neur]; Log.v(TAG,"Current:"+comp+" New:"+neus); }while(comp.contains(neus)); funkSpeech(myTTS,true); setLocale(neus); //beLoud(this.getString(R.string.change_text)); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onGravityChanged(float x, float y, float z) { // TODO Auto-generated method stub Log.v(TAG,"Gravity Changed - x:"+x+" y:"+y+" z:"+z); float sq= (float)x*x+y*y+z*z; float sum=(float)Math.sqrt(sq); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); nikVector temp=new nikVector(); temp.setVector(getTime(),x,y,z); if(prefs.getBoolean("applicationRecording",true))gravvector.add(temp); String debug="LevelActivityDebug"; levelView.updateData(x, y, z,orientation,debug); } @Override public void onAccelerationChanged(float x, float y, float z) { // TODO Auto-generated method stub Log.v(TAG,"Acceleration Changed - x:"+x+" y:"+y+" z:"+z); float sq= (float)x*x+y*y+z*z; float sum=(float)Math.sqrt(sq); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); nikVector temp=new nikVector(); temp.setVector(getTime(),x,y,z); if(prefs.getBoolean("applicationRecording",true))accelvector.add(temp); levelView.updateAccelData(x, y, z,orientation); } @Override public void onMagneticFieldChanged(float x, float y, float z) { // TODO Auto-generated method stub Log.v(TAG,"Magnetic Field Changed - x:"+x+" y:"+y+" z:"+z); float sq= (float)x*x+y*y+z*z; float sum=(float)Math.sqrt(sq); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); nikVector temp=new nikVector(); temp.setVector(getTime(),x,y,z); if(prefs.getBoolean("applicationRecording",true))magvector.add(temp); levelView.updateMagneticData(x, y, z); } @Override public void onShake(float forceacc) { // TODO Auto-generated method stub SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); float force=((float)prefs.getInt("deviceweight",0)/1000)*forceacc; Log.v(TAG,"Force Detected: "+force); beLoud(this.getString(R.string.alert)+(int)force+this.getString(R.string.newton),this.getString(R.string.toast_force)+force+this.getString(R.string.newton_short)); /* String maketext= this.getString(R.string.alert)+(int)force+this.getString(R.string.newton); //Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show(); t1.speak(maketext, TextToSpeech.QUEUE_FLUSH, null); Toast.makeText(getBaseContext(), this.getString(R.string.toast_force)+force+this.getString(R.string.newton_short),Toast.LENGTH_SHORT).show(); */ } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public void onBackPressed() { Log.i(TAG,"LevelActivity.onBackPressed() "); new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getApplicationContext().getString(R.string.dialogue_exit_title)) .setMessage(getApplicationContext().getString(R.string.dialogue_exit_text)) .setPositiveButton(getApplicationContext().getString(R.string.dialogue_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //finish(); exitAll(); } }) .setNegativeButton(getApplicationContext().getString(R.string.dialogue_no), null) .show(); } private void restartTTS(){ Log.v(TAG,"restartTTS()"); myTTS.shutdown(); myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS){ String setlang = mySettings.getString("applicationLanguage","none"); String comp = getResources().getConfiguration().locale.getLanguage(); if (setlang.contains(comp)){ // Toast.makeText(getBaseContext(), "Language is local", Toast.LENGTH_SHORT).show(); // Toast Vorlage } else if (setlang=="none" ) { SharedPreferences.Editor editor = mySettings.edit(); editor.putString("applicationLanguage", comp); editor.commit(); //myTTS.setLanguage(getResources().getConfiguration().locale); //Toast.makeText(getBaseContext(), "Needet to Set Variable", Toast.LENGTH_SHORT).show(); // Toast Vorlage }else { //Toast.makeText(getBaseContext(), "Some Fuckup! Set:"+setlang+", current: "+comp, Toast.LENGTH_SHORT).show(); // Toast Vorlage funkSpeech(myTTS,false); setLocale(setlang); } funkSpeech(myTTS,false); myTTS.setLanguage(getResources().getConfiguration().locale); }else if (status == TextToSpeech.ERROR) { SharedPreferences.Editor editor = mySettings.edit(); editor.putBoolean("applicationTalking", false); editor.commit(); Toast.makeText(getBaseContext(), getApplicationContext().getString(R.string.action_lang_NA), Toast.LENGTH_LONG).show(); } } }); } private int getScreenOrientation() { int rotation = getWindowManager().getDefaultDisplay().getRotation(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; int orientation; // if the device's natural orientation is portrait: if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height) { switch(rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; default: Toast.makeText(getBaseContext(), "Unknown screen orientation. Defaulting to " + "landscape.",Toast.LENGTH_SHORT).show(); orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; } } // if the device's natural orientation is landscape or if the device // is square: else { switch(rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; default: Toast.makeText(getBaseContext(), "Unknown screen orientation. Defaulting to " + "landscape.",Toast.LENGTH_SHORT).show(); orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; } } return orientation; } public void setLocale(String lang) { Log.i(TAG, "LevelActivity.setLocale() "+lang); SharedPreferences.Editor editor = mySettings.edit(); editor.putString("applicationLanguage", lang); editor.commit(); myLocale = new Locale(lang); Configuration config = new Configuration(); config.locale = myLocale; getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics()); /*//langname=lang; Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, LevelActivity.class);*/ //startActivity(refresh); setupActionBar(); myTTS.setLanguage(config.locale); beLoud(this.getString(R.string.change_text)); //myTTS.setLanguage(conf.locale); /*setupActionBar(); t1.setLanguage(getResources().getConfiguration().locale); if(t1.isLanguageAvailable(getResources().getConfiguration().locale) v){ String str=""; for (int i =0;iTextToSpeech.LANG_MISSING_DATA){ //t1.speak(this.getString(R.string.goodby), TextToSpeech.QUEUE_FLUSH, null); //} myTTS.speak(this.getString(R.string.goodby), TextToSpeech.QUEUE_FLUSH, null); Log.i(TAG,"Shutting Down"); while (myTTS.isSpeaking()){ //system.Out.Println("Do something or nothing while speaking..") } myTTS.shutdown(); System.exit(0); } public String getDateCurrentTimeZone(long timestamp) { try{ Calendar calendar = Calendar.getInstance(); TimeZone tz = TimeZone.getDefault(); calendar.setTimeInMillis(timestamp * 1000); calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd__HH-mm-ss"); Date currenTimeZone = (Date) calendar.getTime(); return sdf.format(currenTimeZone); }catch (Exception e) { Log.e(TAG,"Unable to get TimeZone",e); } return ""; } private class ProcessData extends AsyncTask, Float, Integer> { private String filename="newfile"; @Override protected Integer doInBackground(Vector... vects) { String printout=""; //FileOutputStream outputStream; //ArrayList currentAL=new ArrayList(); int count = vects.length; int totalSize = 0; Log.i(TAG,"LevelActivity.AsyncTask.ProcessData() for "+count+"Vectors"); filename=getDateCurrentTimeZone(getTime())+".csv"; File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), filename); //FileOutputStream outputStream = new FileOutputStream(file); //printout=makeReadable(gravvector); //totalSize += gravvector.size(); /* for (int i = 0; i < count; i++) { //currentAL=vects[i]; totalSize +=vects[i].size(); publishProgress((float) ((i / (float) count))); // 0.2 // Escape early if cancel() is called if (isCancelled()) break; printout+=makeReadable(vects[i]); //FileOutputStream stream = new FileOutputStream(file); try { FileWriter fwr = new FileWriter(file); fwr.write(printout); fwr.close(); } catch (Exception e) { Log.e(TAG, "Failed to Write to File:"+filename,e); } } Log.i(TAG,"LevelActivity.AsyncTask.ProcessData() of "+totalSize+"Totalsize"); return totalSize; //return "Executed"; } @Override protected void onPostExecute(Integer result) { //TextView txt = (TextView) findViewById(R.id.output); //txt.setText("Executed"); // txt.setText(result); // might want to change "executed" for the returned string passed // into onPostExecute() but that is upto you //beLoud(getBaseContext().getString(R.string.action_savedata)); /*for (int i = 0; i < vects.length; i++) { vects[i].clear(); }*/ accelvector.clear(); magvector.clear(); gravvector.clear(); Toast.makeText(getBaseContext(),result+"Sets of"+ getBaseContext().getString(R.string.action_savedata), Toast.LENGTH_LONG).show(); } @Override protected void onPreExecute() {} @Override protected void onProgressUpdate(Float... values) {} } public Canvas getDataDrawn(Vector v){ Canvas mycan=new Canvas(); return mycan; } public String makeReadable(Vector v){ String timeline=""; String xline=""; String yline=""; String zline=""; String printout=""; for(int j=0;j