Get the data from sensor and save it somewhere - android

I'm using a sensor connected via Bluetooth who sends info about heart rate, heart beat number, distance, speed and strides.
I've done it, it shows me info about that 5 facts but I don't know how to save them.The sensor sends info very often, about 1 time per second.
I must write it in SQLite and insert data with something that I think is called 'bulk insert' because it works faster than inserting every time the sensor sends data. So, the data must be saved somewhere until the bulk insert into SQLite.
This is my code so far which gets data in real time from the sensor:
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
public class hxmDemo extends Activity {
private static final String TAG = "hxmDemo";
private TextView mTitle;
private TextView mStatus;
private String mHxMName = null;
private String mHxMAddress = null;
private BluetoothAdapter mBluetoothAdapter = null;
private HxmService mHxmService = null;
private void connectToHxm() {
mStatus.setText(R.string.connecting);
if (mHxmService == null)
setupHrm();
if ( getFirstConnectedHxm() ) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mHxMAddress);
mHxmService.connect(device); // Attempt to connect to the device
} else {
mStatus.setText(R.string.nonePaired);
}
}
private boolean getFirstConnectedHxm() {
mHxMAddress = null;
mHxMName = null;
BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = mBtAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
for (BluetoothDevice device : bondedDevices) {
String deviceName = device.getName();
if ( deviceName.startsWith("HXM") ) {
mHxMAddress = device.getAddress();
mHxMName = device.getName();
Log.d(TAG,"getFirstConnectedHxm() found a device whose name starts with 'HXM', its name is "+mHxMName+" and its address is ++mHxMAddress");
break;
}
}
}
return (mHxMAddress != null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.rawdata);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
mTitle = (TextView) findViewById(R.id.title);
if ( mTitle == null ) {
Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
finish();
}
mStatus = (TextView) findViewById(R.id.status);
if ( mStatus == null ) {
Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
finish();
}
mTitle.setText(R.string.hxmDemoAppName);
mStatus.setText(R.string.initializing);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Intent intent = new Intent(this, WelcomeMessage.class);
startActivityForResult( intent , 1 );
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available or not enabled", Toast.LENGTH_LONG).show();
mStatus.setText(R.string.noBluetooth);
} else {
if (!mBluetoothAdapter.isEnabled()) {
mStatus.setText(R.string.btNotEnabled);
Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
} else {
mStatus.setText(R.string.connecting);
connectToHxm();
}
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart");
if (mBluetoothAdapter != null ) {
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
mStatus.setText(R.string.btNotEnabled);
Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
}
} else {
mStatus.setText(R.string.noBluetooth);
Log.d(TAG, "onStart: No blueooth adapter detected, it needs to be present and enabled");
}
}
#Override
public synchronized void onResume() {
super.onResume();
Log.d(TAG, "onResume");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mHxmService != null) {
if (mHxmService.getState() == R.string.HXM_SERVICE_RESTING) {
// Start the Bluetooth scale services
mHxmService.start();
}
}
}
private void setupHrm() {
Log.d(TAG, "setupScale:");
// Initialize the service to perform bluetooth connections
mHxmService = new HxmService(this, mHandler);
}
#Override
public synchronized void onPause() {
super.onPause();
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mHxmService != null) mHxmService.stop();
Log.e(TAG, "--- ON DESTROY ---");
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case R.string.HXM_SERVICE_MSG_STATE:
Log.d(TAG, "handleMessage(): MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case R.string.HXM_SERVICE_CONNECTED:
if ((mStatus != null) && (mHxMName != null)) {
mStatus.setText(R.string.connectedTo);
mStatus.append(mHxMName);
}
break;
case R.string.HXM_SERVICE_CONNECTING:
mStatus.setText(R.string.connecting);
break;
case R.string.HXM_SERVICE_RESTING:
if (mStatus != null ) {
mStatus.setText(R.string.notConnected);
}
break;
}
break;
case R.string.HXM_SERVICE_MSG_READ: {
byte[] readBuf = (byte[]) msg.obj;
HrmReading hrm = new HrmReading( readBuf );
hrm.displayRaw();
break;
}
case R.string.HXM_SERVICE_MSG_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(null),Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
connectToHxm();
return true;
case R.id.quit:
finish();
return true;
case R.id.about: {
/*
* Start the activity that displays our welcome message
*/
Intent intent = new Intent(this, WelcomeMessage.class);
startActivityForResult( intent , 1 );
break;
}
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult " + requestCode);
switch(requestCode)
{
case 1:
break;
}
}
public class HrmReading {
public final int STX = 0x02;
public final int MSGID = 0x26;
public final int DLC = 55;
public final int ETX = 0x03;
private static final String TAG = "HrmReading";
int heartRate;
int heartBeatNumber;
long distance;
long speed;
byte strides;
public HrmReading (byte[] buffer) {
int bufferIndex = 0;
Log.d ( TAG, "HrmReading being built from byte buffer");
try {
heartRate = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
heartBeatNumber = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
distance = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
speed = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
strides = buffer[bufferIndex++];
} catch (Exception e) {
/*
* An exception should only happen if the buffer is too short and we walk off the end of the bytes,
* because of the way we read the bytes from the device this should never happen, but just in case
* we'll catch the exception
*/
Log.d(TAG, "Failure building HrmReading from byte buffer, probably an incopmplete or corrupted buffer");
}
Log.d(TAG, "Building HrmReading from byte buffer complete, consumed " + bufferIndex + " bytes in the process");
dump();
}
private void displayRaw() {
display ( R.id.heartRate, (int)heartRate );
display ( R.id.heartBeatNumber, (int)heartBeatNumber );
display ( R.id.distance, distance );
display ( R.id.speed, speed );
display ( R.id.strides, (int)strides );
}
public void dump() {
Log.d(TAG,"...heartRate "+ ( heartRate ));
Log.d(TAG,"...heartBeatNumber "+ ( heartBeatNumber ));
Log.d(TAG,"...distance "+ ( distance ));
Log.d(TAG,"...speed "+ ( speed ));
Log.d(TAG,"...strides "+ ( strides ));
}
private void display ( int nField, int d ) {
String INT_FORMAT = "%d";
String s = String.format(INT_FORMAT, d);
display( nField, s );
}
private void display ( int nField, long d ) {
String INT_FORMAT = "%d";
String s = String.format(INT_FORMAT, d);
display( nField, s );
}
private void display ( int nField, CharSequence str ) {
TextView tvw = (TextView) findViewById(nField);
if ( tvw != null )
tvw.setText(str);
}
}
}
Does anybody know how to do this?

Well there is few steps, which you have to make:
Create your own class by extending #SQLiteOpenHelper - it will help you to handle your data base
Override #onCreate method - it will were you will execute sql request to create data base. I recommend to move name of keys for columns where you will store above data as static ariables, e.g:
public static final class db {
public static final String DATABASE_TABLE = "data_table";
public static final String KEY_ID = "id";
public static final String KEY_HEART_RATE = "heart_rate";
public static final String KEY_HEART_BEAT_NUMBER = "heart_beat_number";
public static final String KEY_DISTANCE = "distance";
public static final String KEY_SPEED = "speed";
public static final String KEY_STRIDER = "strides";
public static final String CREATE_DATA_TABLE =
"CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
+ KEY_HEART_RATE + " TEXT NOT NULL, "
+ KEY_HEART_BEAT_NUMBER + " TEXT NOT NULL, "
+ KEY_DISTANCE + " TEXT NOT NULL, "
+ KEY_SPEED + " TEXT NOT NULL, "
+ KEY_STRIDER + " TEXT NOT NULL");
and #onCreate may looks like it:
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CSConfig.db.db.CREATE_DATA_TABLE);
} catch (SQLiteException e) {
//Can not create table:
}
}
3.Add method to insert yours data and call everytime when you need save data to db:
public final void insertNewData(String heartRate, String heartBeatNumber, String distance, String speed, String stider, ) {
ContentValues dataRowValues = new ContentValues();
dataRowValues.put(CSConfig.db.db.KEY_HEART_RATE, heartRate);
dataRowValues.put(CSConfig.db.db.KEY_HEART_BEAT_NUMBER, heartBeatNumber);
dataRowValues.put(CSConfig.db.db.KEY_DISTANCE, distance);
dataRowValues.put(CSConfig.db.db.KEY_SPEED, speed);
dataRowValues.put(CSConfig.db.db.KEY_STRIDER, strider);
insert(CSConfig.db.db.DATABASE_TABLE, null, dataRowValues);
}
PS. I've omitted details about opening access to database. You can find more details e.g. here

Related

my service increase memory by 50 MB and not reduced after i stop it

I have this service which send my location to server and get some data from it.
package com.speed00.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.gson.Gson;
import com.speed00.R;
import com.speed00.constant.AppConstant;
import com.speed00.helper.FunctionHelper;
import com.speed00.model.achivment.StepHelper;
import com.speed00.model.ride.RideResultResponse;
import com.speed00.model.ride.UpdateLocationData;
import com.speed00.model.ride.UpdateLocationResponse;
import com.speed00.prefrences.MyPreferences;
import com.speed00.prefrences.MySharedPreference;
import com.speed00.retrofit.ApiUtils;
import com.speed00.stepdetucter.StepDetector;
import com.speed00.stepdetucter.StepListener;
import com.speed00.ui.activity.HomeActivity;
import com.speed00.utils.Logger;
import com.speed00.utils.MySensorEventListener;
import com.speed00.utils.NetworkConnection;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MyService extends Service implements StepListener, SensorEventListener {
// constant
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
private Double locationRange = 1.0;
private String oldDegree;
private boolean isServiceRunning;
private int numSteps = 0;
private final int FINAL_STEP = 15;
private SensorManager sensorManager;
private Sensor accel;
String speed_received = "0";
private boolean pedoMetterHasStarted = false;
String pLatitude;
String pLongitude;
private SensorEventListener eListener;
private Sensor accelerometer, magFieldSensor;
private StepDetector simpleStepDetector;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
// TODO Auto-generated method stub
new Handler().post(new Runnable() {
#Override
public void run() {
speed_received = intent.getStringExtra("current speed");
Logger.e("speed__recv" + speed_received);
if (speed_received != null) {
// setSpeedValue(speed_received);//this method is calling to set speed.
//This method is calling to validate Timer For Ride
if (speed_received.equalsIgnoreCase("0")) {
if (!pedoMetterHasStarted) {
numSteps = 0;
statPedoMeter();
}
}
//Calculating distance value
String latitude = MySharedPreference.getInstance(MyService.this).getLatitude();
String longitude = MySharedPreference.getInstance(MyService.this).getLongitude();
if (TextUtils.isEmpty(pLatitude)) {
pLatitude = latitude;
pLongitude = longitude;
} else {
/*
* if distance is more then 2 km then its calculatiog.
*
* */
Location pLocation = new Location("P");
pLocation.setLongitude(Double.parseDouble(pLatitude));
pLocation.setLongitude(Double.parseDouble(pLongitude));
Location nLocation = new Location("N");
nLocation.setLongitude(Double.parseDouble(latitude));
nLocation.setLongitude(Double.parseDouble(longitude));
Logger.e("distance----" + pLocation.distanceTo(nLocation));
if (pLocation.distanceTo(nLocation) >= 10) {
pLatitude = latitude;
pLongitude = longitude;
}
}
}
}
});
}
};
#Override
public void onCreate() {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
eListener = new MySensorEventListener(this, sensorManager);//for direction
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magFieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
//callback sensor of ui
sensorManager.registerListener(eListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(eListener, magFieldSensor, SensorManager.SENSOR_DELAY_NORMAL);
assert sensorManager != null;
accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
simpleStepDetector = new StepDetector();
simpleStepDetector.registerListener(this);
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
isServiceRunning = true;
// Toast.makeText(getApplicationContext(), "service started", Toast.LENGTH_SHORT).show();
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
// new Timer().scheduleAtFixedRate(new TimeDisplayTimerTask(), 100, NOTIFY_INTERVAL);
runLoop();
LocalBroadcastManager.getInstance(this).registerReceiver(message,
new IntentFilter("send"));
}
private void runLoop() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
updateDriverLocation();
if (isServiceRunning)
runLoop();
}
}, 1000);
}
/*
*
* This method is calling to update driver location
* */
private void updateDriverLocation() {
//Get all user details data.
String userId = MySharedPreference.getInstance(getApplicationContext()).getDriverId();
String latitudeData = MySharedPreference.getInstance(getApplicationContext()).getLatitude();
String longitudeData = MySharedPreference.getInstance(getApplicationContext()).getLongitude();
String speedData = MySharedPreference.getInstance(getApplicationContext()).getSpeedData();//how to roinf
Logger.e("SERVER " + latitudeData + " " + longitudeData);
Logger.e("SPEED " + speedData);
String directionValue = MySharedPreference.getInstance(getApplicationContext()).getDirectionValue();
String speeding = MySharedPreference.getInstance(getApplicationContext()).getSpeeding();
String language = MyPreferences.newInstance(getApplicationContext()).getLanguage();//send speeding data to bakend.
String directionText = MySharedPreference.getInstance(getApplicationContext()).getDirectionText();
long driveTime = FunctionHelper.getDifference(MySharedPreference.getInstance(getApplicationContext()).getStartTime());
String validateUTurn = validateUTurn();
// Logger.e("update_request--" + request);
ApiUtils.getAPIService().updateDriverLocation(validateUTurn, directionText, speeding, "" + driveTime, language, userId,
AppConstant.START_RIDE, speedData, directionValue, latitudeData, longitudeData).enqueue(new Callback<UpdateLocationResponse>() {
#Override
public void onResponse(Call<UpdateLocationResponse> call, Response<UpdateLocationResponse> response) {
if (response.isSuccessful()) {
UpdateLocationResponse updateLocationResponse = response.body();
if (updateLocationResponse.getErrorCode().equalsIgnoreCase(AppConstant.ERROR_CODE)) {
if (updateLocationResponse.getData().size() > 0) {
UpdateLocationData updateLocationData = updateLocationResponse.getData().get(0);
String eventData = FunctionHelper.validateData(updateLocationData);
broadCastEventData(eventData, updateLocationResponse.getErrorCode());
broadCastResponseData(updateLocationResponse);
}
}
}
}
#Override
public void onFailure(Call<UpdateLocationResponse> call, Throwable t) {
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
/*
*
*This method is calling to validateUTurn.
*
*
* */
private String validateUTurn() {
String currentDegree = MySharedPreference.getInstance(this).getDirectionValue();
String uTurnStatus = "0";
if (TextUtils.isEmpty(oldDegree)) {
oldDegree = currentDegree;
uTurnStatus = "0";
return uTurnStatus;
} else {
if (oldDegree == "0.0") {
oldDegree = currentDegree;
}
if (Float.parseFloat(oldDegree) <= Float.parseFloat(currentDegree)) {
uTurnStatus = "1";
} else {
uTurnStatus = "0";
}
if (Float.parseFloat(oldDegree) == 360 || Float.parseFloat(oldDegree) > 270) {
if (Float.parseFloat(currentDegree) > 0 && Float.parseFloat(oldDegree) <= 90) {
uTurnStatus = "1";
}
}
oldDegree = currentDegree;
return uTurnStatus;
}
}
public synchronized void broadCastEventData(String eventData, String errorCode) {
Intent intent = new Intent("event_broad_cast");
intent.putExtra("data", eventData);
intent.putExtra("error", errorCode);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
/*
* This method is calling to broadcast event data
* */
/*
* This method is calling to broadcast event data
* */
public synchronized void broadCastResponseData(UpdateLocationResponse updateLocationData) {
Intent intent = new Intent("location_update");
Bundle args = new Bundle();
args.putSerializable("data", (Serializable) updateLocationData);
intent.putExtra("myvalue", args);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
LocalBroadcastManager.getInstance(this).unregisterReceiver(message);
// stopPedoMeter();
}
#Override
public void step(long timeNs) {
if (numSteps < 16)
Toast.makeText(this, "" + numSteps, Toast.LENGTH_SHORT).show();
saveStep();
if (calculateSteps()) {
stopRideAfter25step();
stopPedoMeter();//this method is calling to stop ResultActivity
} else if (Double.parseDouble(MySharedPreference.getInstance(this).getSpeedData()) > 10) {
MySharedPreference.getInstance(this).setSteps(new ArrayList<StepHelper>());
numSteps = 0;
} else {
Logger.e("stepsss " + numSteps);
numSteps = numSteps + 1;
}
}
private void stopRideAfter25step() {
MySharedPreference.getInstance(this).setSteps(new ArrayList<StepHelper>());
String speed = MySharedPreference.getInstance(this).getSpeedData();
String direction = MySharedPreference.getInstance(this).getDirectionValue();
String latitude = MySharedPreference.getInstance(this).getLatitude();
String longitude = MySharedPreference.getInstance(this).getLongitude();
String driverId = MySharedPreference.getInstance(this).getDriverId();
String language = MyPreferences.newInstance(this).getLanguage();
String speeding = MySharedPreference.getInstance(this).getSpeeding();
long driveTime = FunctionHelper.getDifference(MySharedPreference.getInstance(this).getStartTime());
//validate internet connection
if (NetworkConnection.isConnection(this)) {
stopRide("" + driveTime, language, speeding, driverId, latitude, longitude, AppConstant.STOP_RIDE, speed, direction);
} else {
Toast.makeText(this, getString(R.string.valid_please_check_network_connection), Toast.LENGTH_LONG).show();
}
}
public void stopRide(final String driveTime, final String languageKey, final String speedLimit, final String driverId, final String latitude, final String longitude, String rideStatus, final String speed, final String direction) {
String[] param = {driveTime, languageKey, speedLimit, driverId, speed, direction, latitude, longitude};
new stopLoc(this).execute(param);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
simpleStepDetector.updateAccel(event.timestamp, event.values[0], event.values[1], event.values[2]);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private static class stopLoc extends AsyncTask<String[], Void, Void> {
Context mContext;
public stopLoc(Context mContext) {
this.mContext = mContext;
}
#Override
protected Void doInBackground(String[]... strings) {
Logger.e("stepsss stopingggg");
String driveTime = strings[0][0];
String languageKey = strings[0][1];
String speedLimit = strings[0][2];
String driverId = strings[0][3];
String speed = strings[0][4];
String direction = strings[0][5];
String latitude = strings[0][6];
String longitude = strings[0][7];
ApiUtils.getAPIService().stopTrip(driveTime, languageKey, speedLimit, driverId, AppConstant.STOP_RIDE, speed, direction, latitude, longitude).enqueue(new Callback<RideResultResponse>() {
#Override
public void onResponse(Call<RideResultResponse> call, Response<RideResultResponse> response) {
Logger.e("response----" + new Gson().toJson(response.body()));
if (response.isSuccessful()) {
String errorCode = response.body().getErrorCode();
if (errorCode.equalsIgnoreCase(AppConstant.ERROR_CODE)) {
tripSuccessData(response.body(), mContext);
} else {
Toast.makeText(mContext, "" + mContext.getString(R.string.text_some_erroroccurs), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<RideResultResponse> call, Throwable t) {
Toast.makeText(mContext, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return null;
}
}
public static void tripSuccessData(Object data, Context context) {
RideResultResponse resultResponse = (RideResultResponse) data;
if (resultResponse.getErrorCode().equalsIgnoreCase(AppConstant.ERROR_CODE)) {
FunctionHelper.enableUserIntraction();
HomeActivity.bSpeedStatus = false;
Intent intent = new Intent("trip_ended");
intent.putExtra("trip_info", resultResponse.getData().get(0));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
((MyService) context).stopSelf();
} else {
Toast.makeText(context, resultResponse.getErrorMsg(), Toast.LENGTH_SHORT).show();
}
}
private boolean calculateSteps() {
ArrayList<StepHelper> arrayList = MySharedPreference.getInstance(this).getSteps();
ArrayList<StepHelper> newList = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
long seconds = FunctionHelper.getDifference(arrayList.get(i).getTime());
if ((int) seconds < 180) {
newList.add(arrayList.get(i));
}
}
if (numSteps - newList.get(0).getSteps() >= FINAL_STEP) {
return true;
} else {
MySharedPreference.getInstance(this).setSteps(newList);
return false;
}
}
private void saveStep() {
ArrayList<StepHelper> arrayList = MySharedPreference.getInstance(this).getSteps();
if (arrayList == null) {
arrayList = new ArrayList<>();
}
arrayList.add(new StepHelper(FunctionHelper.getCurrentDateWitTime(), numSteps));
MySharedPreference.getInstance(this).setSteps(arrayList);
}
private void statPedoMeter() {
// Toast.makeText(this, "start count", Toast.LENGTH_SHORT).show();
pedoMetterHasStarted = true;
MySharedPreference.getInstance(this).setStartPedoMeterTime(FunctionHelper.getCurrentDateWitTime());//store current time
if (sensorManager != null)
sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
}
/*
* This method is calling to stop pedo meter
*
* */
private void stopPedoMeter() {
numSteps = 0;
pedoMetterHasStarted = false;
sensorManager.unregisterListener(this, accelerometer);
sensorManager.unregisterListener(this, accel);
sensorManager.unregisterListener(this, magFieldSensor);
sensorManager = null;
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
Logger.e("MyService --- " + "isRuning");
if (HomeActivity.bSpeedStatus) {
updateDriverLocation();
}
}
});
}
}
}
My app starts and use only 170 MB , but after starting this service , it becomes 220 MB and after finishing it, it still 220 and if i open it again , ram become 240 and if i finish it still 240 and if i open it again it become 260 and so on until app crash
what's the wrong in the service ?
i make sure that it's stopped but don't know why ram not reduced after this service is finished
Try this approache, don't put the stopSelf() inside a static method. Instead, you should call startService again and add an action to the Intent.
So this is how an example actionable service should look like:
public class ExampleService
extends Service {
public static final String START_SERVICE_ACTION = "com.example.action.START_SERVICE";
public static final String STOP_SERVICE_ACTION = "com.example.action.STOP_SERVICE";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String intentAction = intent.getAction();
switch (intentAction) {
case START_SERVICE_ACTION:
//
break;
case STOP_SERVICE_ACTION:
stopSelf();
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Used only in case if services are bound (Bound Services).
return null;
}
}
Interact with the Service from somewhere:
Start with it like this:
Intent service = new Intent(context, ExampleService.class);
service.setAction(NotificationService.START_SERVICE_ACTION);
startService(service);
Stop it like this:
Intent service = new Intent(context, ExampleService.class);
service.setAction(NotificationService.STOP_SERVICE_ACTION);
startService(service);
You don't really need to pass the START_SERVICE_ACTION in this example, just added it to better understand the design.

How to read two BLE characteristics of two services at the same interface page?

I am trying to manage my temperature service and LED service of my BLE device at the same Android interface. However, whenever I try to turn the LED on, the app dies, and I don't know how to fix this (I am not good at either Java or BLE).
I have all of the UUIDs of the characteristics and services I need. I am trying to create two BluetoothGattCharacteristic
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
It works fine when I call the temperature characteristic and get the temperature measurement. However, the app dies whenever I try to turn the LED on /call the LED characteristic.
10-30 08:48:33.026 1033-1033/com.example.android.bluetoothlegatt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.bluetoothlegatt, PID: 1033
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothGattCharacteristic.setValue(byte[])' on a null object reference
at com.example.android.bluetoothlegatt.AutoConnectActivity.turnLEDon(AutoConnectActivity.java:71)
at com.example.android.bluetoothlegatt.AutoConnectActivity$6.onClick(AutoConnectActivity.java:264)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19754)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5219)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The following code is how I transfer all characteristics & services together.
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
if ( gattCharacteristic.getUuid().equals(UUID.fromString(SampleGattAttributes.CTRL_2))){ //CTRL_2 is the UUID of my LED characteristic
Log.e(TAG, "GattCharacteristics= " + gattCharacteristic.getUuid());
Intent intent = new Intent(DeviceControlActivity.this, AutoConnectActivity.class);
intent.putExtra("character_id", "F000AA01-0451-4000-B000-000000000000"); //UUID of my temperature characteristic
intent.putExtra("service_id", "F000AA00-0451-4000-B000-000000000000");//UUID of my temperature service
intent.putExtra("address", mDeviceAddress);
intent.putExtra("ctrl2_character_id", gattCharacteristic.getUuid().toString()); //UUID of my LED characteristics
intent.putExtra("ctrl2_service_id", gattCharacteristic.getService().getUuid().toString());//UUID of my LED service
startActivity(intent);
}
The part I fail is the function that I try to turn LED on.
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
The following is my complete code of trying to manipulate two characteristics at the same interface.
package com.example.android.bluetoothlegatt;
public class AutoConnectActivity extends Activity {
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
private String address;
private UUID serviceId;
private UUID charId;
private UUID ctrl2ServiceId;
private UUID ctrl2CharId;
private TextView debugText;
private Button startBtn;
private Button stopBtn;
private Button ctrlStartBtn;
private Button ctrlStopBtn;
private Timer timer = new Timer();
private boolean started = false;
private ArrayAdapter<String> adapter;
private String Entry;
private File file;
private boolean check= true;
private BluetoothLeService mBluetoothLeService;
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
public boolean turnLEDoff()
{
byte[] value = {(byte)0};
characteristicCTRL2.setValue(value);
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return !status;
};
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
mBluetoothLeService.connect(address);
}
};
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(address);
List<BluetoothGattService> list = mBluetoothLeService.getSupportedGattServices();
for(BluetoothGattService s : list){
if(s.getUuid().compareTo(serviceId) == 0){
if (check==true) {
characteristic = s.getCharacteristic(charId);
mBluetoothLeService.disconnect();
}
return;
}
if(s.getUuid().compareTo(ctrl2ServiceId) == 0){
if(check==false) {
characteristicCTRL2 = s.getCharacteristic(ctrl2CharId);
}
return;
}
}
mBluetoothLeService.disconnect();
Log.e(TAG, "not find device");
debugText.setText("not find device");
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
debugText.setText(action);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
// if temperature measurement
if (check==true){
mBluetoothLeService.readCharacteristic(characteristic);}
// if control LED
if(check==false){
mBluetoothLeService.readCharacteristic(characteristicCTRL2);
turnLEDon();
}
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))
{
if (check==false) {
String CTRL_Status = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("CTRL Status: " + CTRL_Status + " " + new Date(System.currentTimeMillis()));
turnLEDoff();
mBluetoothLeService.disconnect();
}
if(check==true) {
String temperature = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("Temperature: " + temperature + "°C " + new Date(System.currentTimeMillis()));
Entry = address + "," + new Date(System.currentTimeMillis()).toString() + "," + temperature.toString() + "\n";
try {
FileOutputStream out = new FileOutputStream(file, true);
out.write(Entry.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mBluetoothLeService.disconnect();
}
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autoconnect);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
address = intent.getStringExtra("address");
serviceId = UUID.fromString(intent.getStringExtra("service_id"));
charId = UUID.fromString(intent.getStringExtra("character_id"));
ctrl2ServiceId = UUID.fromString(intent.getStringExtra("ctrl2_service_id"));
Log.e(TAG, " CTRL2 SERVICE: " + ctrl2ServiceId);
ctrl2CharId = UUID.fromString(intent.getStringExtra("ctrl2_character_id"));
Log.e(TAG, " CTRL2 CHARAC: " + ctrl2CharId);
((TextView)findViewById(R.id.address_txt)).setText(address);
((TextView)findViewById(R.id.service_txt)).setText(serviceId.toString());
((TextView)findViewById(R.id.char_txt)).setText(charId.toString());
debugText = (TextView)findViewById(R.id.debug_txt);
startBtn = (Button)findViewById(R.id.start_btn);
stopBtn = (Button)findViewById(R.id.stop_btn);
ctrlStartBtn = (Button)findViewById(R.id.ctrl_start_btn);
ctrlStopBtn = (Button)findViewById(R.id.ctrl_stop_btn);
ListView listView = (ListView)findViewById(R.id.result_list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started) return;
started = true;
check=true;
//External Storage
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File Dir = new File(root.getAbsolutePath() + "/MeasurementDataFile");
if (!Dir.exists()) {
Dir.mkdir();
}
file = new File(Dir, "Temperature.csv");
}
if (check==true){
timer.schedule(timerTask, 0, 1000 * 5); }
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=true;
timer.cancel();
}
});
ctrlStartBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mBluetoothLeService.connect(address);
check=false;
if(started) return;
started = true;
Toast.makeText (getBaseContext(), "Turn CTRL 1 ON", Toast.LENGTH_SHORT).show();
Log.e(TAG, " On?: " + turnLEDon());
}
});
ctrlStopBtn.setOnClickListener(new View.OnClickListener() {
//mBluetoothLeService.connect(address);
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=false;
Log.e(TAG, " Off?: " + turnLEDoff());
Toast.makeText (getBaseContext(), "Turn CTRL 1 OFF", Toast.LENGTH_SHORT).show();
}
});
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, DeviceControlActivity.makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(address);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
}
All BLE calls are asynchronous. This is really pain-in-neck, but we have what we have. So you cannot just write:
{
boolean status = writeCharacteristic(characteristic);
return status;
}
and hope all will be ok. In this case, you obtain a result of the writeCharacteristic instruction only, but not the real write operation result! For the last, you need to register the part of your code as BluetoothGattCallback descendant and read OnCharacteristicWrite event, where you can really know the result of your write operation.
All BLE read-write operations should be done in a strict one-by-one sequence and from main app thread only.
Different devices have different capabilities and productivity, so you can obtain different results - IMHO, this is less strange, than Google's decision to realize BLE stack in this manner :)
Pretty BLE guide for Android can be found here: https://droidcon.de/sites/global.droidcon.cod.newthinking.net/files/media/documents/practical_bluetooth_le_on_android_0.pdf
Edit
The link above is broken but the other one can be found here:
https://speakerdeck.com/erikhellman/practical-bluetooth-low-energy-on-android

android PDF rendering issue

I am realizing pdf viewer function using APV library
when I load pdf file using APV library I mentioned, some part of pages are invisible and sometimes not.
Invisible parts are sometimes paragraph and sometimes picture etc. I think it does not depend on object but trial.
Does anyone have similar problem? If anyone knows, please let me know.
I attached 2 picture that have same page, one normal and the other abnormal.
abnormal
normal
public class mPDFActivity extends PdfViewerActivity {
byte[] startSign = {0x31};
byte[] stopSign = {0x32};
public static boolean isPDFPageRunning = false; // bluetoothservice에서 이 activity로 신호 보낼 때 해당 변수 상태 보고 동작(page 넘김) 할지 말지 결정
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
public int getMenuOpenFile() {return R.drawable.openfile;}
public int getMenuScanBluetooth() {return R.drawable.ic_action_device_access_bluetooth_searching;}
public Handler PDFHandler;
mPDFActivity currentActivity;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig .orientation == newConfig.ORIENTATION_LANDSCAPE)
{
}else{
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
isPDFPageRunning = true;
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
//FragmentActivity activity = getActivity();
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_LONG).show();
this.finish();
}
byte a[] = {(byte)0x01, (byte)0xff};
if(a[1] == -1) {
int re = Conversion.ByteArraytoInteger(a[0], a[1]);
}
Log.d(TAG,"KK");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pref = getSharedPreferences("PDF",0);
SharedPreferences.Editor edit = pref.edit();
if(isAlreadyCreated)
{
}else{
}
edit.putFloat(Constants.ZOOM, mZoom);
edit.putInt(Constants.PAGE, mPage);
edit.commit();
}
#Override
protected void onResume() {
isPDFPageRunning = true;
super.onResume();
float zoom;
int page;
SharedPreferences pref = getSharedPreferences(Constants.PDF, 0);
zoom = pref.getFloat(Constants.ZOOM,1);
page = pref.getInt(Constants.PAGE,1);
if(!isAlreadyCreated){
}
}
#Override
protected void onStop() {
isPDFPageRunning = false;
super.onStop();
}
#Override
protected void onDestroy() {
isPDFPageRunning = false;
super.onDestroy();
mChatService.write(stopSign);
if (mChatService != null) {
mChatService.stop();
}
}
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
//public BluetoothChatService mChatService = null;
public BluetoothChatService mChatService = null;
ArrayAdapter adapter;
int clickCounter=0;
ArrayList listItems=new ArrayList();
private File[] imagelist;
String[] pdflist;
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
private void setupChat() {
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
//setupChat();
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
this.finish();
}
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//Activity activity = getApplicationContext();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(getString(R.string.title_connecting));
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(getString(R.string.title_not_connected));
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
break;
case Constants.MESSAGE_READ:
/*
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.what);
//Log.i(TAG,readMessage);
//mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
int bytes = msg.arg1; // length of read bytes array
String str = Conversion.byteArraytoHexString(readBuf).substring(0, bytes * 2);
str = str.substring(str.indexOf("ff"));
while(str.length() >= 10)
{
String datA = str.substring(2,5);
String datB = str.substring(6,9);
int dat1 = Conversion.hexStringtoInteger(datA);
int dat2 = Conversion.hexStringtoInteger(datB);
//TODO: 데이터 저장 및 신호처리
str = str.substring(10);
}
Log.e("READ","READ : " + str);
*/
//TODO : mPDFActivity로 메시지에 따른 intent 날려
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
mChatService.write(startSign);
}
break;
case Constants.MESSAGE_TOAST:
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_PREV_PAGE:
prevPage();
break;
case Constants.MESSAGE_NEXT_PAGE:
nextPage();
break;
case Constants.MESSAGE_VIBRATE:
Vibrator vb = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
int duration = msg.getData().getInt(Constants.VIBRATE);
vb.vibrate(duration);
break;
}
}
};
/**
* Establish connection with other divice
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
Activity activity = this;
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
}

Recieving data on Android app from imu and after displaying save in .csv file

As I am receiving data from imu razor 9 degree of freedom,(giving me the value of accelerometer,gyro,and magnetometer) we can burn code in it with the help of Arduino IDE.
So, currently I am receiving data on my Android app as shown in image is like that and in my Android code I am updating receiving code here private void: updateReceivedData(byte[] data)
So when I append data to show my values it works fine like that: mDumpTextView.append(message);
But according to requirement, I want that data in array so I can easily display that specific value on screen, not the whole data and at the same time. I need data to store in .csv file . but I am not able to do this . When I use to save in arraym it doesn't work for me: data obtain from imu in an append form in Android app
The whole code is available on GitHub:
https://github.com/mik3y/usb-serial-for-android/tree/master/usbSerialExamples/src/main
But in the code:
public class SerialConsoleActivity extends Activity {
private final String TAG = SerialConsoleActivity.class.getSimpleName();
/**
* Driver instance, passed in statically via
* {#link #show(Context, UsbSerialPort)}.
*
* <p/>
* This is a devious hack; it'd be cleaner to re-create the driver using
* arguments passed in with the {#link #startActivity(Intent)} intent. We
* can get away with it because both activities will run in the same
* process, and this is a simple demo.
*/
private static UsbSerialPort sPort = null;
private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private CheckBox chkDTR;
private CheckBox chkRTS;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
#Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
#Override
public void onNewData(final byte[] data) {
SerialConsoleActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
SerialConsoleActivity.this.updateReceivedData(data);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_console);
// mDumpTextView = (TextView) findViewById(R.id.consoleText);
mTitleTextView = (TextView) findViewById(R.id.demoTitle);
mDumpTextView = (TextView) findViewById(R.id.consoleText);
// mDumpTextView = (TextView) findViewById(R.id.ex);
mScrollView = (ScrollView) findViewById(R.id.demoScroller);
chkDTR = (CheckBox) findViewById(R.id.checkBoxDTR);
chkRTS = (CheckBox) findViewById(R.id.checkBoxRTS);
chkDTR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
sPort.setDTR(isChecked);
}catch (IOException x){}
}
});
chkRTS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
sPort.setRTS(isChecked);
}catch (IOException x){}
}
});
}
#Override
protected void onPause() {
super.onPause();
stopIoManager();
if (sPort != null) {
try {
sPort.close();
} catch (IOException e) {
// Ignore.
}
sPort = null;
}
finish();
}
void showStatus(TextView theTextView, String theLabel, boolean theValue){
String msg = theLabel + ": " + (theValue ? "enabled" : "disabled") + "\n";
theTextView.append(msg);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Resumed, port=" + sPort);
if (sPort == null) {
mTitleTextView.setText("No serial device.");
} else {
final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
if (connection == null) {
mTitleTextView.setText("Opening device failed");
return;
}
try {
sPort.open(connection);
sPort.setParameters(57600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
showStatus(mDumpTextView, "CD - Carrier Detect", sPort.getCD());
// sPort.getCD();
showStatus(mDumpTextView, "CTS - Clear To Send", sPort.getCTS());
//sPort.getCTS();
showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
//sPort.getDSR();
showStatus(mDumpTextView, "DTR - Data Terminal Ready", sPort.getDTR());
//sPort.getDTR();
showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
//sPort.getDSR();
showStatus(mDumpTextView, "RI - Ring Indicator", sPort.getRI());
//sPort.getRI();
showStatus(mDumpTextView, "RTS - Request To Send", sPort.getRTS());
//sPort.getRTS();
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
mTitleTextView.setText("Error opening device: " + e.getMessage());
try {
sPort.close();
} catch (IOException e2) {
// Ignore.
}
sPort = null;
return;
}
mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
}
onDeviceStateChange();
}
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
public void writeToCsv1(String x,String y,String z) throws IOException {
Calendar c = Calendar.getInstance();
File folder = new File(Environment.getExternalStorageDirectory() + "/project");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String csv = folder + "/AccelerometerValue1.csv";
FileWriter file_writer = new FileWriter(csv, true);
;
String s = c.get(Calendar.YEAR) + "," + c.get(Calendar.MONTH) + "," + c.get(Calendar.DATE) + "," + c.get(Calendar.HOUR) + "," + c.get(Calendar.MINUTE) + "," + c.get(Calendar.SECOND) + "," + c.get(Calendar.MILLISECOND) + "," + x + "," + y + "," + z + "\n";
file_writer.append(s);
file_writer.close();
}
}
private void startIoManager() {
if (sPort != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private String convert(byte[] data) {
StringBuilder sb = new StringBuilder(data.length);
for (int i = 0; i < data.length; ++ i) {
if (data[i] < 0) throw new IllegalArgumentException();
sb.append((char) data[i]);
}
return sb.toString();
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
private void updateReceivedData(byte[] data) {
final String message = convert(data);
if (convert(data) =="A") {
mDumpTextView.append("\n\n");
}
mDumpTextView.append(message);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
/**
* Starts the activity, using the supplied driver instance.
*
* #param context
* #param driver
*/
static void show(Context context, UsbSerialPort port) {
sPort = port;
final Intent intent = new Intent(context, SerialConsoleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
[enter image description here][1]}

Suggestions as to why application cant pick up connected clients (Code Provided)

Hey guys ive been working on a project to create a type of wifi hot spot manager, so that it records the connected devices with mac address, ip address and other information. However i can't seem to work out as to why when i press get Clients from screen it doesn't gather any data of whos connected. I have compiled the file to an APK to test on my phone seeing as wifi functionality does not work on the emulator in android studio.
Credit for the code goes to:
1) Android 2.3 wifi hotspot API
2) https://www.whitebyte.info/android/android-wifi-hotspot-manager-class
package com.example.gavin.wifiattendance;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import android.os.Handler;
/**
* Created by Gavins on 05/03/2015.
*/
public class AccessPoint extends Activity {
private static int constant = 0;
private Context context;
private static int WIFI_STATE_UNKNOWN = -1;
private static int WIFI_STATE_DISABLING = 0;
private static int WIFI_STATE_DISABLED = 1;
public static int WIFI_STATE_ENABLING = 2;
public static int WIFI_STATE_ENABLED = 3;
private static int WIFI_STATE_FAILED = 4;
final static String[] WIFI_STATE_TEXTSTATE = new String[]{
"DISABLING","DISABLED","ENABLING","ENABLED","FAILED"
};
private WifiManager wifi;
private String TAG = "WifiAP";
private int stateWifi = -1;
private boolean alwaysEnabledWifi = true;
//enable or disable the wifi
public void toggleWifiAP(WifiManager wifiHandler, Context context){
if (wifi == null){
wifi = wifiHandler;
}
boolean wifiApIsOn = getWifiApState() == WIFI_STATE_ENABLED || getWifiApState()==WIFI_STATE_ENABLING;
new SetWifiApTask(!wifiApIsOn, false, context).execute();
}
private int setWifiApEnabled(boolean enabled){
Log.d(TAG, "Set wifi enabled called" + enabled);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "Attend Lecture";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
//remember wireless state
if (enabled && stateWifi == -1){
stateWifi = wifi.getWifiState();
}
//disable the wireless
if (enabled && wifi.getConnectionInfo() !=null){
Log.d(TAG, "disable wifi: calling");
wifi.setWifiEnabled(false);
int loopMax = 10;
while (loopMax > 0 && wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED){
Log.d(TAG, "Disable Wifi: Waiting, pass:" + (10-loopMax));
try{
Thread.sleep(500);
loopMax--;
}catch (Exception e){
e.printStackTrace();
}
}
Log.d(TAG, "Disabling wifi is done, pass: " + (10-loopMax));
}
//enable and disable wifi AP
int state = WIFI_STATE_UNKNOWN;
try {
Log.d(TAG, (enabled?"enabling":"Disabling")+"wifi ap: calling");
wifi.setWifiEnabled(false);
Method method1 = wifi.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method1.invoke(wifi, config, enabled);
Method method2 = wifi.getClass().getMethod("getWifiState");
state = (Integer)method2.invoke(wifi);
}catch (Exception e){
//Log.e(WIFI_SERVICE, e.getMessage());
}
//Use thread while processing occurs
if (!enabled){
int loopMax = 10;
while (loopMax>0 && (getWifiApState()==WIFI_STATE_DISABLING || getWifiApState()==WIFI_STATE_ENABLED || getWifiApState()==WIFI_STATE_FAILED)){
Log.d(TAG, (enabled?"enabling": "disabling")+ "wifi AP: waiting, pass:" + (10-loopMax));
try {
Thread.sleep(500);
loopMax--;
}catch (Exception e){
}
}
Log.d(TAG, (enabled?"enabling":"disabling")+" Wifi ap: done, pass: " + (10-loopMax));
//enable the wifi
if (stateWifi==WifiManager.WIFI_STATE_ENABLED || stateWifi==WifiManager.WIFI_STATE_ENABLING || stateWifi==WifiManager.WIFI_STATE_UNKNOWN || alwaysEnabledWifi){
Log.d(TAG, "enable wifi: Calling");
wifi.setWifiEnabled(true);
//this way it doesnt hold things up and waits for it to get enabled
}
stateWifi = -1;
}else if (enabled){
int loopMax = 10;
while (loopMax>0 && (getWifiApState()==WIFI_STATE_ENABLING || getWifiApState()==WIFI_STATE_DISABLED || getWifiApState()==WIFI_STATE_FAILED)){
Log.d(TAG, (enabled?"Enabling": "disabling") + "wifi ap: waiting, pass: " + (10-loopMax));
try{
Thread.sleep(500);
loopMax--;
}catch (Exception e){
}
}
Log.d(TAG, (enabled?"Enabling": "disabling")+ "wifi ap: done, pass: " + (10-loopMax));
}
return state;
}
//Get the wifi AP state
public int getWifiApState(){
int state = WIFI_STATE_UNKNOWN;
try {
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
}catch (Exception e){
}
if (state>=10){
constant=10;
}
WIFI_STATE_DISABLING = 0+constant;
WIFI_STATE_DISABLED = 1+constant;
WIFI_STATE_ENABLING = 2+constant;
WIFI_STATE_ENABLED = 3+constant;
WIFI_STATE_FAILED = 4+constant;
Log.d(TAG, "getWifiApState " + (state==-1?"UNKNOWN":WIFI_STATE_TEXTSTATE[state-constant]));
return state;
}
class SetWifiApTask extends AsyncTask<Void, Void, Void>{
boolean mMode;
boolean mFinish;
ProgressDialog pDialog;
public SetWifiApTask(boolean mode, boolean finish, Context context){
mMode = mode;
mFinish = finish;
pDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.setTitle("Turning on Access Point " + (mMode?"On":"Off" + "..."));
pDialog.setMessage("Please wait a moment...");
pDialog.show();
}
#Override
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
try {
pDialog.dismiss();
MainActivity.updateStatusDisplay();
}catch (IllegalArgumentException e){
};
if (mFinish){
finish();
}
}
#Override
protected Void doInBackground(Void... params) {
setWifiApEnabled(mMode);
return null;
}
}
//get the list connected to the wifi hotspot
public void getClientList(boolean onlyReachable, FinishScanListener finishListener){
getClientList(onlyReachable, 300, finishListener);
}
public void getClientList(final boolean onlyReachable, final int reachableTimeout, final FinishScanListener finishListener){
Runnable runnable = new Runnable() {
#Override
public void run() {
BufferedReader br = null;
final ArrayList<ClientScanResult> result = new ArrayList<>();
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null){
String[] splitted = line.split(" +");
if ((splitted !=null) && (splitted.length >=4)){
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")){
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachable || isReachable){
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
}
}
}
}
}catch (Exception e){
Log.e(this.getClass().toString(), e.toString());
}finally {
try {
br.close();
}catch (IOException e){
Log.e(this.getClass().toString(), e.getMessage());
}
}
//Get handler that will be used to post to main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
finishListener.onFinishScan(result);
}
};
mainHandler.post(myRunnable);
}
};
Thread myThread = new Thread(runnable);
myThread.start();
}
}
and here is the main activity file:
package com.example.gavin.wifiattendance;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.example.gavin.wifiattendance.AccessPoint;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
wifiAP = new AccessPoint();
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
scan();
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
public void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
Edit: commented out the main looper made it work but after taking out the comments, the application now crashes on launch
http://gyazo.com/fa068fd1fce3f27f43185c0cd12568c1

Categories

Resources