I have written the following lines to record accelerometer data in a file with a button click
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
xAxis_lateralA = sensorEvent.values[0];
yAxis_longitudinalA = sensorEvent.values[1];
zAxis_verticalA = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
textView.append("\nACC_x = "+ xAxis_lateralA + ", ACC_y = "+yAxis_longitudinalA+ ", ACC_z = " + zAxis_verticalA);
acc+="\n"+xAxis_lateralA + ", "+ yAxis_longitudinalA+", "+zAxis_verticalA;
try {
File myFile = new File("/sdcard/acc.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(acc);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'acc.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
// write on SD card file data in the text box
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
int sensorType = Sensor.TYPE_ACCELEROMETER;
sm.registerListener(mySensorEventListener,sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
}// onClick
});
Now I want it to stop recording the data with another button click. For example -
stopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int sensorType = Sensor.TYPE_ACCELEROMETER;
sm.unregisterListener(listener, sensor)
}// onClick
}); // btnstopButton
}
Wanted to use unregisterListener but most of the time it is saying deprecated.
Can anyone help please?
The documentation says that using the methods associated with SensorListener are deprecated, and to use SensorEventListener instead. Your code snippet should not throw a deprecated warning, but if you use SensorListener, it would.
I think you want to declare your SensorEventListener object outside of the onClick() method so you can unregister it in the other onClick() method:
sm.unregisterListener(mySensorEventListener, sensorType);
That's the method signature you want to use according to the docs.
Related
I am using the below code to Play Audio file (.wav), but it plays the file with Echo(like playing two voice simultaneously) when activity is in Landscape mode.
public class Find_n_Display_StationActivity extends Activity
{
GPSTracker gps;
TextView txtvw,locNameTV;
boolean calculating_distance=false;
ArrayList<String>data=new ArrayList<String>();
ArrayList<String>latArray=new ArrayList<String>();
ArrayList<String>longArray=new ArrayList<String>();
MySQLiteHelper db = new MySQLiteHelper(this);
ImageView profileIV;
PendingIntent intent;
String reached_station="empty";
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.find_n__display__statn_activity);
txtvw=(TextView)findViewById(R.id.textView2);
locNameTV=(TextView)findViewById(R.id.textView1);
profileIV=(ImageView)findViewById(R.id.image11);
profileIV.setVisibility(View.GONE);
//Put in LANDSCAPE MODE...
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Show FULL-SCREEN Activity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Calling/Starting Thread to Handl Uncaught Exeption
Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);
//(((( This will retrieve DATA from service to this Activity ))))
gps = new GPSTracker(this);
LocalBroadcastManager.getInstance(this.getApplicationContext()).registerReceiver(
mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
// mp=new MediaPlayer();
}//EOF Oncreate Method...
//(((( This Function is Called if App Crash, So, App is start Automatically after crash ))))
private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread thread, Throwable ex)
{
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
};
// (((( This Class Get Data From Service class GPSTracker.class() ))))
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("Status");
Bundle b = intent.getBundleExtra("Location");
Location lastKnownLoc = (Location) b.getParcelable("Location");
if (lastKnownLoc != null)
{
String s1=String.valueOf(lastKnownLoc.getLatitude());
String s2=String.valueOf(lastKnownLoc.getLongitude());
double current_lat=Double.parseDouble(s1);
double current_long=Double.parseDouble(s2);
txtvw.setText("____________________________\n\n\n"+current_lat+"\n"+current_long);
//showtoast("You have changed your Location");
if(calculating_distance==false)
{
calculating_distance=true;
FindDistance(current_lat,current_long);
}
Turn_On_Screen();
}
}};
private String stationPlayed="empty";
#SuppressWarnings("deprecation")
public void Turn_On_Screen()
{
WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
//later
//screenLock.release();
}
//(((( Find Distance Betwee All Points ))))))
public void FindDistance(double current_lat,double current_long)
{
Move_App_Back_to_ForeGround();
ArrayList<String>stationNameArray=new ArrayList<String>();
ArrayList<String>imageArray=new ArrayList<String>();
ArrayList<String>voiceArray=new ArrayList<String>();
imageArray=db.Get_ImageList();
voiceArray=db.Get_VoiceList();
stationNameArray=db.Get_StionNameAraay();
latArray=db.Get_LatAraay();
longArray=db.Get_LongAraay();
float smallest_dis=10000;
String next_station="";
boolean found_station=false;
for(int i=1;i<latArray.size();i++)
{
float lat1 = Float.parseFloat(latArray.get(i));
float long1 = Float.parseFloat(longArray.get(i));
float dis=FindDistance((float)current_lat,(float)current_long,lat1, long1);
if(dis<smallest_dis)
{
smallest_dis=dis;
next_station=stationNameArray.get(i);
}
if(dis<=50)
{
Set_Pic_n_Voice(imageArray.get(i),voiceArray.get(i),stationNameArray.get(i));
// showtoast("station-name="+ stationNameArray.get(i));
break;
}
}
locNameTV.setText("You are Heading towards Station="+next_station+"\n You are only "+smallest_dis+" Meter away...");
calculating_distance=false;
}
public void Set_Pic_n_Voice(String image,final String voice,final String station_name)
{
DisplayImage(image);
if(!reached_station.equalsIgnoreCase(station_name))
reached_station=""+station_name; //Don't play voice for same station just display pic always
//Wait for 4 seconds to play this voice
Runnable r = new Runnable()
{
public void run()
{
if(!stationPlayed.equalsIgnoreCase(station_name))
{
PlayVoice(voice);
stationPlayed=station_name;
}
}
};
android.os.Handler h = new android.os.Handler();
h.postDelayed(r, 5000);// */
}
//(((( Displaying Picture For the Station ))))
public void DisplayImage(String image)
{
profileIV.setVisibility(View.VISIBLE);
File imageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Images",image);
if (imageFile.exists())
{
File imgFile = new File(imageFile.getAbsolutePath()); // path of your file
Picasso.with(this).load(Uri.fromFile(new File(imageFile.getAbsolutePath()))).into(profileIV);
/*
FileInputStream fis = null;
try {
fis = new FileInputStream(imgFile);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
//options.inPurgeable = true;
// options.inScaled = true;
Bitmap bm = BitmapFactory.decodeStream(fis, null,options);
profileIV.setImageBitmap(bm);//*/
}
else
profileIV.setImageResource(R.drawable.default_station_pic);
}
//(((( Playing Voice For The Station ))))))
public void PlayVoice(String voice)
{
calculating_distance=true;
// Play_Audio_File ob=new Play_Audio_File(this);
//ob.PlayVoice(voice);
File voiceFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Voices",voice);
if (voiceFile.exists())
{
if(!mp.isPlaying())
{
mp.reset();
try {
mp.setDataSource(voiceFile.getAbsolutePath());
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
calculating_distance=false;
}
});
}
else
{
//mp.reset();
mp= MediaPlayer.create(this, R.drawable.default_station_voice);
if(!mp.isPlaying())
{
mp.start();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
calculating_distance=false;
}
});
}
//*/
}
//((((( Find distance between two geolocation )))
public float FindDistance(float lat1, float lng1, float lat2, float lng2)
{
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
//((( Move App To Screen from Background ))))
public void Move_App_Back_to_ForeGround()
{
boolean foregroud=false;
try
{
foregroud = new ForegroundCheckTask().execute(getApplicationContext()).get();
} catch (InterruptedException e)
{ e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
if(!foregroud)
{
//Open Activity IF it is in Background...
Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(this.getPackageName(), Find_n_Display_StationActivity.class.getName()));
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.getApplicationContext().startActivity(it);
}
}
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
#Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
//SHOW-TOAST-MESSAGE
public void showtoast(String str)
{
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
public void OnBackPressed()
{
}
}//EOF Activity...
You are somehow calling the PlayVoice() method twice. The reason your inner if statement isn't preventing this is because you must be calling mp = new MediaPlayer(); before calling PlayVoice(), otherwise the first call to that method would result in a NullPointerException from the mp.isPlaying() call in the if condition. Since mp now points to a new MediaPlayer instance, isPlaying() returns false, and the if block executes again, even though the previous instance is still playing.
To prevent multiple instances of MediaPlayer playing concurrently, instantiate the MediaPlayer only once in the declaration line, remove the mp = new MediaPlayer(); line in PlayVoice() (and anywhere else you might have it), and un-comment the mp.reset(); call there.
The PlayVoice() method is being called twice because you're requesting an orientation change to landscape in the Activity's onCreate() method, and you're not handling configuration changes yourself. This is causing the Activity started in portrait mode to be destroyed and recreated, which means that onCreate() runs a second time, but the MediaPlayer started in the first Activity instance is still playing when a new one is created and started in the second instance.
You can prevent this from happening by forcing the Activity to launch in a landscape orientation from the start. You can do this by adding android:screenOrientation="landscape" to the <activity>'s tag in the manifest. You can also remove the setRequestedOrientation() call now, as it is no longer needed.
I have a variable MyFinalPressure which is populated with sensor data from the sensors pressure. If MyFinalPressure is == to 4000 (4000 points or 40 sec) then stop writing to local storage.
But it looks like when I debug the code, it hits the boolean MaxPoints and is still writing. I wonder if my logic is wrong or not.
Could you please help me out.
public Boolean Store = false;
Boolean MaxPoints = false;
if (activity.Store) {
activity.writeToFile(MyFinalPressure);//MyFinalPressure is float of one dimension array or stream of array.
}
if (MyFinalPressure==4000){ //this conditon, am trying to stop wrting to local memory.
activity.MaxPoints = true;
}
FileOutputStream fileOutputStream;
//method to write into local memory.
public void writeToFile(final float MyFinalPressure) {
Log.d(TAG, "writeToFile.");
String finalData;
finalData = String.valueOf(MyFinalPressure);
try {
// true here for 'append'
fileOutputStream = new FileOutputStream(file, true);
String Space = " ";
byte[] convert = Space.getBytes();
fileOutputStream.write(finalData.getBytes());
fileOutputStream.write(convert);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//write to file.
StartWriting = (ToggleButton) findViewById(R.id.startWriting);
StartWriting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (StartWriting.isChecked()) {
Store = true;
Toast.makeText(getApplicationContext(), "Data Starts writing into (Message.txt) file", Toast.LENGTH_LONG).show();
} else {
if (!StartWriting.isChecked()|| MaxPoints==true) { //here - this is wrong logic to stop writing to my file.
Toast.makeText(getApplicationContext(), "Data Stored at myAppFile", Toast.LENGTH_SHORT).show();
String finalData1;
finalData1 = String.valueOf(fileOutputStream);
Log.i(TAG, "of_writes: " + finalData1);
// Toast.makeText(getApplicationContext(), "Data_write_number: " + finalData1.length(), Toast.LENGTH_SHORT).show();
Store = false;
}
}
}
});
Just take out !StartWriting.isChecked()
Because of the above if statement StartWriting.isChecked() will always be false. Then because you are checking for "!StartWriting.isChecked()" it will always enter the statement.
Hey:) I am trying to pasre to accelerometer data into an xml file when the start button is clicked but the problem is it only parses me the first accelerometer data so not the others or if i write it like the code down here it parse 1000 times the same value
Thank you
public class Secondet extends Activity implements SensorEventListener {
TextView currentX;
TextView currentY;
TextView currentZ;
TextView locationx;
TextView locationy;
float deltaX = 0;
float deltaY = 0;
float deltaZ = 0;
double X = 0;
double Y = 0;
protected LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
initializeViews();
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
public void initializeViews() {
currentX = (TextView) findViewById(R.id.currentX);
currentY = (TextView) findViewById(R.id.currentY);
currentZ = (TextView) findViewById(R.id.currentZ);
final Button start = (Button) findViewById(R.id.start);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
float lastX = 0, lastY = 0, lastZ = 0;
deltaX = (Math.abs(lastX - event.values[0]));
deltaY = (Math.abs(lastY - event.values[1]));
deltaZ = (Math.abs(lastZ - event.values[2]));
displayCurrentValues();
}
public void location() {
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
X = location.getLongitude();
Y = location.getLatitude();
}
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
final Button start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
parse();
}
});
}
public void parse() {
String xAxis = Float.toString(deltaX);
String yAxis = Float.toString(deltaY);
String zAxis = Float.toString(deltaZ);
// Creat XML File
File newxmlfile = new File(Environment.getExternalStorageDirectory()
+ "/newtest1.xml");
try {
newxmlfile.createNewFile();
} catch (IOException e) {
Log.e("IOException", "exception in createNewFile() method");
}
// we have to bind the new file with a FileOutputStream
FileOutputStream fileos = null;
try {
fileos = new FileOutputStream(newxmlfile);
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
XmlSerializer serializer = Xml.newSerializer();
try {
// we set the FileOutputStream as output for the serializer, using
// UTF-8 encoding
serializer.setOutput(fileos, "UTF-8");
// Write <?xml declaration with encoding (if encoding not null) and
// standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
// set indentation option
serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output",
true);
// start a tag called "root"
serializer.startTag(null, "root");
// i indent code just to have a view similar to xml-tree
// int i = 0;
final Button stop = (Button) findViewById(R.id.Stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
int i = 2;
}
});
for (int i = 0; i <= 1000; i++) {
// serializer.startTag(null, "Location");
// serializer.startTag(null, "Longitude");
// serializer.text(locationX);
// serializer.endTag(null, "Longitude");
// serializer.startTag(null, "Latitude");
// serializer.text(locationY);
// serializer.endTag(null, "Latitude");
// serializer.endTag(null, "Location");
serializer.startTag(null, "Acceleration");
serializer.startTag(null, "X-Axis");
serializer.text(Float.toString(deltaX));
serializer.endTag(null, "X-Axis");
serializer.startTag(null, "Y-Axis");
serializer.text(Float.toString(deltaX));
serializer.endTag(null, "Y-Axis");
serializer.startTag(null, "Z-Axis");
serializer.text(Float.toString(deltaX));
serializer.endTag(null, "Z-Axis");
serializer.endTag(null, "Acceleration");
}// while(i == 0);
serializer.endTag(null, "root");
serializer.endDocument();
// write xml data into the FileOutputStream
serializer.flush();
// finally we close the file stream
fileos.close();
Toast.makeText(getApplicationContext(),
"file has been created on SD card)", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Log.e("Exception", "error occurred while creating xml file");
}
}
}
You need to make a loop. Right now, your code simply calls "parse" once, and that's why it parses that same value 1000 times. Make multiple operations:
An operation that opens the XML File
An operation that closes the XML File
An operation that adds the value to the XML File
When the start button is pressed, initialize the XML File. Then, each time onSensorChanged( ) is called, add the values to the XML File. Once you have 1000 values (implement a simple counter), turn off the accelerometer and call the operation that closes the XML File. The XML File will need to be a global variable, not a local variable, so that all operations can access it.
I have made some apps (pedometer, heart rate, audio recorder) for the moto360 with android wear. everything works fine, but I don't know how to save the data on the watch and how to access the data on the smartphone. I have managed to send messages to the watch, but I can't send data from the watch to the phone. I can save my data on the smartphone, but I don't know how to manage it on the smartwatch. can someone show me a tutorial or an example? thank you so much!
edit:
The following Code below is used for tracking the heartrate on the Moto360 and it works fine.
I tried to transfer the data from the watch to the Phone for that I used this tutorial -> https://developer.android.com/training/wearables/data-layer/data-items.html
After implementing the Code from the android page I couldn`t run the Project on the device!
public class MainActivity extends Activity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewStepCount;
private TextView mTextViewStepDetect;
private TextView mTextViewHeart;
PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextViewStepCount = (TextView) stub.findViewById(R.id.step_count);
mTextViewStepDetect = (TextView) stub.findViewById(R.id.step_detect);
mTextViewHeart = (TextView) stub.findViewById(R.id.heart);
getStepCount();
}
});
}
private void getStepCount() {
SensorManager mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
Sensor mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Sensor mStepCountSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
Sensor mStepDetectSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mStepCountSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mStepDetectSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private String currentTimeStr() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(c.getTime());
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int) event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
} else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
String msg = "Count: " + (int) event.values[0];
mTextViewStepCount.setText(msg);
Log.d(TAG, msg);
} else if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
String msg = "Detected at " + currentTimeStr();
mTextViewStepDetect.setText(msg);
Log.d(TAG, msg);
} else {
Log.d(TAG, "Unknown sensor type");
}
}
}
this code helps me a lot, i hope it helps many other people :)
https://github.com/pocmo/SensorDashboard
You need to uses data assets. Image sample:
private static Asset createAssetFromBitmap(Bitmap bitmap) {
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
return Asset.createFromBytes(byteStream.toByteArray());
}
and then
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Asset asset = createAssetFromBitmap(bitmap);
PutDataRequest request = PutDataRequest.create("/image");
request.putAsset("profileImage", asset);
Wearable.DataApi.putDataItem(mGoogleApiClient, request);
more http://developer.android.com/training/wearables/data-layer/assets.html
I'm simply trying to record accelerometer data and write a file in sdcard with a button click. While running the app in my Nexus S (with 4.1.2), it freezes after a minute. I tried to run it in Galaxy Nexus phone and it works smoothly. For some reasons I have to work in Nexus S. Can anyone suggest me what might be the reason of crashing. I tried to see the log, but it does not through any error message.
Here's my code:
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
xAxis_lateralA = sensorEvent.values[0];
yAxis_longitudinalA = sensorEvent.values[1];
zAxis_verticalA = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
textView.append("\nACC_x = "+ xAxis_lateralA + ", ACC_y = "+yAxis_longitudinalA+ ", ACC_z = " + zAxis_verticalA);
acc += "\n"+miliSec()+", "+xAxis_lateralA + ", "+ yAxis_longitudinalA+", "+zAxis_verticalA;
try {
File myFile = new File("/sdcard/acc.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(acc);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Done writing SD 'acc.txt'",Toast.LENGTH_SHORT).show();
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
int sensorType = Sensor.TYPE_ACCELEROMETER;
sm.registerListener(mySensorEventListener,sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
}// onClick
}); // btnWriteSDFile
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int sensorType = Sensor.TYPE_ACCELEROMETER;
sm.unregisterListener(mySensorEventListener, sm.getDefaultSensor(sensorType));
Toast.makeText(getBaseContext(), "Stopped Recording",Toast.LENGTH_SHORT).show();
finish();
}// onClick
}); // btnstopButton
Issue is due to the way your writing values to text file.
You are opening/writing/closiing the file for everytime you get sensor reading.
Even for Sensor reading frequency of 50Hz it takes lot computation,writing these in text for 50 times/second is not efficient.
Use BufferedWriter ,it gives better performance.