MainActivity.java 7.12 KB
package com.example.filewrite;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;


public class MainActivity extends Activity implements SensorEventListener{
	int count;
	//Button btn;
	ToggleButton tb;
	TextView tvX,tvY,tvZ,tvCount;
	private static final String TAG = "MEDIA";
	private SensorManager senSensorManager;
	private Sensor senAccelerometer;
	private StringBuilder data;
	String outputFilename;
	ToneGenerator toneG;
	ProgressBar Zbar;
	ProgressBar Ybar;
	ProgressBar Xbar;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        outputFilename = "";
        data = new StringBuilder(300000);
        count = 0;
        //btn = (Button) findViewById(R.id.button1);
        tb = (ToggleButton)findViewById(R.id.switchBtn);
        tvX = (TextView) findViewById(R.id.tvX);
        tvY = (TextView) findViewById(R.id.tvY);
        tvZ = (TextView) findViewById(R.id.tvZ);
        tvCount = (TextView) findViewById(R.id.tvCount);
        senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_FASTEST);
        toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
        Xbar = (ProgressBar) findViewById(R.id.progressBar1);
        Ybar = (ProgressBar) findViewById(R.id.progressBar2);
        Zbar = (ProgressBar) findViewById(R.id.progressBar3);
        Xbar.setMax(11);
        Ybar.setMax(11);
        Zbar.setMax(11);
//        btn.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				save();
//			}
//		});
        tb.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				if(outputFilename == ""){
					Toast.makeText(getBaseContext(),"Please set the output file first",Toast.LENGTH_LONG).show();
					tb.setChecked(false);
				}else{
					if(tb.isChecked()){
						try {
							Thread.sleep(10000, 0);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					toneG.startTone(ToneGenerator.TONE_DTMF_0, 600); 
				}
				
			}
		});
    }
    
    private void save(){
    	int status = writeToSDFile(data.toString());
		if(status == 0){
			data = new StringBuilder(300000);
		}else{
			 Toast.makeText(getBaseContext(),"Error while saving...",Toast.LENGTH_SHORT).show();
		}
    }
    
    private int writeToSDFile(String s){

        // Find the root of the external storage.
        // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal

        File root = android.os.Environment.getExternalStorageDirectory(); 

        //Toast.makeText(getBaseContext(),"\nExternal file system root: "+root,Toast.LENGTH_SHORT).show();
        // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

        File dir = new File (root.getAbsolutePath() + "/download");
        dir.mkdirs();
        File file = new File(dir, outputFilename);

        try {
        	FileWriter fw = new FileWriter(file,true);
        	fw.write(s);
        	fw.close();
//            FileOutputStream f = new FileOutputStream(file);
//            
//            PrintWriter pw = new PrintWriter(f);
////            pw.println("Hi , How are you");
////            pw.println("Hello");
//            pw.println(s);
//            pw.flush();
//            pw.close();
//            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i(TAG, "******* File not found. Did you" +
                    " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
            return 1;
        } catch (IOException e) {
            e.printStackTrace();
            return 2;
        }   

        Toast.makeText(getBaseContext(),"File written to "+file,Toast.LENGTH_SHORT).show();
        return 0;
    }
    
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
        	AlertDialog.Builder alert = new AlertDialog.Builder(this);

        	alert.setTitle("Output");
        	alert.setMessage("Please insert output filename.");

        	// Set an EditText view to get user input 
        	final EditText input = new EditText(this);
        	alert.setView(input);

        	alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int whichButton) {
        	  // Do something with value!
        	  Toast.makeText(getBaseContext(),"Filename Set",Toast.LENGTH_SHORT).show();
        	  outputFilename = input.getText().toString();
        	  }
        	});

        	alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	  public void onClick(DialogInterface dialog, int whichButton) {
        	    // Canceled.
        	  }
        	});

        	alert.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent arg0) {
		// TODO Auto-generated method stub
		tvX.setText("X: "+String.format("%.3f%n",arg0.values[0]));
		tvY.setText("Y: "+String.format("%.3f%n",arg0.values[1]));
		tvZ.setText("Z: "+String.format("%.3f%n",arg0.values[2]));
		Xbar.setProgress((int)arg0.values[0]);
		Ybar.setProgress((int)arg0.values[1]);
		Zbar.setProgress((int)arg0.values[2]);
		if(tb.isChecked()){
			count++;
			tvCount.setText("Count: "+String.valueOf(count));
			data.append(count+","+arg0.values[0]+","+arg0.values[1]+","+arg0.values[2]+"\n");
			if(count%1000 == 0){
				save();
				toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 150); 
			}
		}
		
	}
}