I implemented program to calculate co-ordinates, pressure, orientation, finger size etc on blackcanvas(canvas). But I need to calculate these on top of every application. That is on top of PDF, web browser etc. i.e. It should run as a background process. It has to capture every touch instances of screen. I should bind screen to canvas.
public class CaptureEventsActivity extends Activity implements OnTouchListener {
String root = android.os.Environment.getExternalStorageDirectory().toString();
File mydir = new File(root + "/saved_texts");
File file1 = new File(mydir,"Research.xls");
FileOutputStream out_stream;
FileOutputStream out_stream1;
Float azimut;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.BOTTOM;
WindowManager wm1 = (WindowManager) getSystemService(WINDOW_SERVICE);
BlankCanvas bcan = new BlankCanvas(this,null);
this.setContentView(bcan);
bcan.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("NewApi")
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
BlankCanvas bcn = (BlankCanvas) arg0;
int pointerIndex = event.getActionIndex();
int pointerId = event.getPointerId(pointerIndex);
int maskedAction = event.getActionMasked();
switch(maskedAction) {
case MotionEvent.ACTION_DOWN:
{
//EventData eventData = new EventData();
handler.postDelayed(CaptureEventsActivity.this.mLongPressed, 1000);
GesturePoint gp = new GesturePoint(event.getX(),event.getY(),System.currentTimeMillis());
aa.add(gp);
//bcn.path.moveTo(event.getX(), event.getY());
touchDirection = getTouchDirection(event.getX(), event.getY());
String strD = String.valueOf((int)event.getX()) +'\t'+ String.valueOf((int)event.getY()) +'\t'+ String.valueOf(event.getOrientation())+'\t' +event.getPressure()+'\t'+event.getEventTime()+'\t'+"ACTION_DOWN"+'\t'+event.getSize()+'\t'+ touchDirection+'\t'+'\n';
try {
out_stream.write(strD.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;}
case MotionEvent.ACTION_MOVE:
{
if(event.getPointerCount()>1)
{
for (int size = event.getPointerCount(), i = 0; i < size; i++) {
PointF point = mActivePointers.get(event.getPointerId(i));
if (point != null) {
//bcn.path.lineTo(event.getX(i), event.getY(i));
String x="";
//if(i==1)
x="finger:"+i;
//touchDirection = getTouchDirection(event.getX(i), event.getY(i));
String strM = String.valueOf((int)event.getX(i)) +'\t'+ String.valueOf((int)event.getY(i)) +'\t'+ String.valueOf(event.getOrientation(i))+'\t' +event.getPressure(i)+'\t'+event.getEventTime()+'\t'+"ACTION_MOVE"+'\t'+event.getSize(i)+'\t'+ touchDirection+'\t'+x+'\n';
try {
out_stream.write(strM.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else
{
handler.removeCallbacks(CaptureEventsActivity.this.mLongPressed);
//bcn.path.lineTo(event.getX(), event.getY());
//touchDirection = getTouchDirection(event.getX(i), event.getY(i));
String strM = String.valueOf((int)event.getX()) +'\t'+ String.valueOf((int)event.getY()) +'\t'+ String.valueOf(event.getOrientation())+'\t' +event.getPressure()+'\t'+event.getEventTime()+'\t'+"ACTION_MOVE"+'\t'+event.getSize()+'\t'+ touchDirection+'\t'+'\n';
try {
out_stream.write(strM.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
case MotionEvent.ACTION_POINTER_DOWN:
{
PointF f = new PointF();
handler.postDelayed(CaptureEventsActivity.this.mLongPressed, 1000);
GesturePoint gp = new GesturePoint(event.getX(),event.getY(),System.currentTimeMillis());
aa.add(gp);
f.x = event.getX(pointerIndex);
f.y = event.getY(pointerIndex);
// bcn.path.moveTo(event.getX(), event.getY());
touchDirection = getTouchDirection(event.getX(), event.getY());
String strA = String.valueOf((int)f.x) +'\t'+ String.valueOf((int)f.y) +'\t'+ String.valueOf(event.getOrientation())+'\t' +event.getPressure()+'\t'+event.getEventTime()+'\t'+"ACTION_POINTER_DOWN"+'\t'+event.getSize()+'\t'+ touchDirection+'\t'+'\n';
mActivePointers.put(pointerId, f);
try {
out_stream.write(strA.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
PointF f = new PointF();
handler.postDelayed(CaptureEventsActivity.this.mLongPressed, 1000);
GesturePoint gp = new GesturePoint(event.getX(),event.getY(),System.currentTimeMillis());
aa.add(gp);
f.x = event.getX(pointerIndex);
f.y = event.getY(pointerIndex);
mActivePointers.put(pointerId, f);
// bcn.path.moveTo(event.getX(), event.getY());
touchDirection = getTouchDirection(event.getX(), event.getY());
String strU = String.valueOf((int)event.getX()) +'\t'+ String.valueOf((int)event.getY()) +'\t'+ String.valueOf(event.getOrientation())+'\t' +event.getPressure()+'\t'+event.getEventTime()+'\t'+"ACTION_POINTER_UP"+'\t'+event.getSize()+'\t'+ touchDirection+'\t'+'\n';
try {
out_stream.write(strU.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
case MotionEvent.ACTION_UP:
{ handler.removeCallbacks(CaptureEventsActivity.this.mLongPressed);
GesturePoint gp = new GesturePoint(event.getX(),event.getY(),System.currentTimeMillis());
aa.add(gp);
GesturePoint gp1= new GesturePoint(event.getOrientation(),event.getPressure(),event.getAction());
aa.add(gp1);
//GestureStroke gs = new GestureStroke(aa);
touchDirection = getTouchDirection(event.getX(), event.getY());
String strU = String.valueOf((int)event.getX()) +'\t'+ String.valueOf((int)event.getY()) +'\t'+ String.valueOf(event.getOrientation())+'\t' +event.getPressure()+'\t'+event.getEventTime()+'\t'+"ACTION_UP"+'\t'+event.getSize()+'\t'+ touchDirection+'\t'+'\n';
try {
out_stream.write(strU.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
aa.clear();
}
break;
default:
/*String x =String.valueOf(bcn.getX())+'\n';
try {
out_stream.write(x.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return false;
}
bcn.invalidate();
return true;
}
});
//}
//wm1.addView(bcan, params);
bcan.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Log.e("CaptureEvent", "in long preess...");
long_clicks++;
return true;
}
});
}
//#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
try {
//String w_s = "No.of strikes..." + String.valueOf(no_of_strikes) + '\n';
//out_stream.write(w_s.getBytes());
//w_s = "No.of Long Clicks..."+String.valueOf(long_clicks) + '\n';
//out_stream.write(w_s.getBytes());
out_stream.flush();
out_stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getTouchDirection (float eventX, float eventY) {
String direction = "";
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics( metrics );
float centreX = 800; /// metrics.widthPixels * eventX;
float centreY = 480; /// metrics.heightPixels * eventY;
// float centreX = 400/2, centreY = 700/2;
float tx = (float) (eventX - centreX), ty = (float) (eventY - centreY);
float radius = (float) Math.sqrt(tx*tx + ty*ty);
float offsetX = 0, offsetY = radius, adjEventX = eventX - centreX, adjEventY = centreY - eventY;
double cosaU = ((offsetX * adjEventX) + (offsetY * adjEventY));
double cosaD = ( Math.sqrt((offsetX * offsetX) + (offsetY * offsetY)) * Math.sqrt((adjEventX * adjEventX) + (adjEventY * adjEventY)));
double cosa = cosaU / cosaD;
double degr = ( Math.acos(cosa) * (180 / Math.PI));
if (adjEventX < 0)
degr = 360 - degr;
float offsetDegrees = (float) (degrees + degr);
if (offsetDegrees > 360)
offsetDegrees = offsetDegrees - 360;
if (offsetDegrees < 22.5 || offsetDegrees > 336.5)
direction = "NORTH";
else if (offsetDegrees > 22.5 && offsetDegrees < 67.5)
direction = "NORTHEAST";
else if (offsetDegrees > 67.5 && offsetDegrees < 112.5)
direction = "EAST";
else if (offsetDegrees > 112.5 && offsetDegrees < 156.5)
direction = "SOUTHEAST";
else if (offsetDegrees > 156.5 && offsetDegrees < 201.5)
direction = "SOUTH";
else if (offsetDegrees > 201.5 && offsetDegrees < 246.5)
direction = "SOUTHWEST";
else if (offsetDegrees > 246.5 && offsetDegrees < 291.5)
direction = "WEST";
else if (offsetDegrees > 291.5 && offsetDegrees < 336.5)
direction = "NORTHWEST";
return direction;
}
}
So using WindowManager.LayoutParams
when I am calling wm1.addView(bcan, params);
It is throwing an error
You should have your activity implements OnTouchListener, not SensorEventListener.
public class CaptureEventsActivity extends Activity implements OnTouchListener {
...
// Set the listener as itself
setOnTouchListener(CaptureEventsActivity.this);
...
#Override
public boolean onTouch(View v, MotionEvent event) {
// Do things here
}
}
By the way, you might not want to do everything in onCreate(), creating methods like setView() do things related with the view would be better. It does no harm, just a good habbit.
Hope this helps (:
Related
When the strobe value is increased from 1 to 10 the blinking of flashlight will never stop.neither it stops on zero nor it turns on beside it just get blinking and blinking constantly. here i am adding the code which i have written to do so. if someone knows the solutions please help me.
Thread is not stop thread works until you stop debugger..
cheers!
enter code here
flashButton = findViewById(R.id.flash_button);
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
flashButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (!isTorchOn) {
turnOnFlashLight();
} else {
turnOffFlashLight();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
scrollValue = findViewById(R.id.value);
mWheel = findViewById(R.id.wheel);
mWheel.setOnScrollListener(new Wheel.OnScrollListener() {
#Override
public void onScrollStarted(Wheel view, float value, int roundValue) {
frequency = Math.abs(roundValue);
}
#Override
public void onScrollFinished(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
thread = new Thread(stroboRunner);
thread = null;
strobe(frequency);
}
else if(isTorchOn) {
strobe(0);
// thread.stop();
// thread=null;
}
}
#Override
public void onScroll(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
// thread = null;
strobe(frequency);
}
}
});
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOnFlashLight() {
/*
if(frequency > 0){
scrollValue.setText("0.0");
}
*/
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
} else {
try {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(camParams);
cam.startPreview();
} catch (RuntimeException e) {
Toast.makeText(this, "Camera Permission is not granted", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_on);
isTorchOn = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
mCameraManager.setTorchMode(mCameraId, false);
}
} else {
try {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
cam.stopPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception throws in turning off flashlight.", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_off);
isTorchOn = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private int strobeFrequency(int roundValue) {
int freq = 0;
switch (roundValue) {
case 1:
freq = Math.abs(50);
break;
case 2:
freq = Math.abs(150);
break;
case 3:
freq = Math.abs(300);
break;
case 4:
freq = Math.abs(600);
break;
case 5:
freq = Math.abs(900);
break;
case 6:
freq = Math.abs(1200);
break;
case 7:
freq = Math.abs(1500);
break;
case 8:
freq = Math.abs(1800);
break;
case 9:
freq = Math.abs(2000);
break;
case 10:
freq = Math.abs(2300);
break;
}
return freq;
}
#Override
protected void onResume() {
super.onResume();
try {
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
} catch (Exception e) {
// TODO: handle exception
}
compass.start();
}
#Override
protected void onPause() {
super.onPause();
compass.stop();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "stop compass");
compass.stop();
}
private void strobe(int freq) {
if(thread == null){
stroboRunner = new StroboRunner();
stroboRunner.freq = freq;
thread = new Thread(stroboRunner);
thread.start();
} else if(freq == 0 && thread!=null) {
stroboRunner.stopRunning = true;
thread = null;
// thread.stop();
}
}
private class StroboRunner implements Runnable {
int freq;
boolean stopRunning = false;
#Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
while (!stopRunning) {
mCameraManager.setTorchMode(mCameraId, true);
Thread.sleep(2600 - freq);
System.out.println(""+(2600-freq));
// Toast.makeText(MainActivity.this, ""+(2600-freq), Toast.LENGTH_SHORT).show();
mCameraManager.setTorchMode(mCameraId, false);
Thread.sleep(freq);
}
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// thread=null;
} else {
Camera.Parameters paramsOn = cam.getParameters();
Camera.Parameters paramsOff = camParams;
paramsOn.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
cam.setParameters(paramsOn);
cam.startPreview();
Thread.sleep(2600 - freq);
cam.setParameters(paramsOff);
cam.startPreview();
Thread.sleep(freq);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
I have a simple bluetooth code to activate a relay.
it is from an old project and it used to work fine, but I was sending just bit in the past, this time I have to send strings.
With this code I can send six command and then the device doesn't respond anymore. when I stop the application suddenly all the commands "un-executed" before are executed by the relay board. If I change the size of the buffer it seems to have some effect on the number of messages I can send.
I am using an old phone a controller with Android 2 and API 10
Any idea where I should investigate?
Thanks
public class Menuuu extends Activity {
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
String a;
Editable b;
final byte[] buffer = new byte[2048];
private ToggleButton T1;
private static final String TAG = "MyActivity";
public void write_buf(byte[] buffer) {
try {
mmOutputStream.write(buffer, 0, 1024 );
mmOutputStream.flush();
} catch (IOException e) { }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ToggleButton T1 = (ToggleButton) findViewById(R.id.Button1);
T1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (T1.isChecked()) {
// TODO Auto-generated method stub
buffer[0] = 'r';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'a';
buffer[4] = 'y';
buffer[5] = ' ';
buffer[6] = 'o';
buffer[7] = 'n';
buffer[8] = ' ';
buffer[9] = '0';
buffer[10] = ' ';
buffer[11] = '\r';
buffer[12] = '\n';
}
if (!T1.isChecked()) {
// TODO Auto-generated method stub
buffer[0] = 'r';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'a';
buffer[4] = 'y';
buffer[5] = ' ';
buffer[6] = 'o';
buffer[7] = 'f';
buffer[8] = 'f';
buffer[9] = ' ';
buffer[10] = '0';
buffer[11] = '\r';
buffer[12] = '\n';
}
write_buf(buffer);
}
});
void findBT() throws IOException
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals(a))
{
mmDevice = device;
break;
}
}
}
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater h= getMenuInflater();
h.inflate(R.menu.hardmenu,menu);
return true;
}
I'm trying to write on a file the readings of the sensors. I have this code.. I need to see the data i'm writing but I don't know how to access to it. I downloaded the File Manager for android wear but It doesn't allow me to enter to the Storage folder. Below is my code, hope you can help it
public class Logging extends Activity implements SensorEventListener {
DecimalFormat df =new DecimalFormat("##.##");
public static final String file=("Project.txt");
Boolean flag=true;
FileOutputStream outputStream;
TextView displayReading1;
TextView displayReading2;
TextView displayReading3;
TextView displayReading4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logging);
Button start=(Button)findViewById(R.id.StartButton);
Button stop=(Button)findViewById(R.id.StopButton);
//BUTTON START
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=true;
}
}); {
}
//BUTTON STOP
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=false;
}
});{
}
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor rotSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Sensor gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor gyroSensor = sensorManager.getDefaultSensor((Sensor.TYPE_GYROSCOPE));
sensorManager.registerListener(this, accSensor, 100000);
sensorManager.registerListener(this, rotSensor, 100000);
sensorManager.registerListener(this, gravitySensor, 100000);
sensorManager.registerListener(this, gyroSensor, 100000);
displayReading1 = (TextView) findViewById(R.id.acc_sensor);
displayReading2 = (TextView) findViewById(R.id.rotational_sensor);
displayReading3 = (TextView) findViewById(R.id.gravity_sensor);
displayReading4 = (TextView) findViewById(R.id.gyro_sensor);
displayReading1.setTextSize(14f);
displayReading2.setTextSize(14f);
displayReading3.setTextSize(14f);
displayReading4.setTextSize(14f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logging, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
displayReading1.setText("Accelerometer (m/s2): " +"\nX"+" " +df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X11=event.values[0];
float X12=event.values[1];
float X13=event.values[2];
if( flag) {
try {
outputStream = openFileOutput(file, Context.MODE_PRIVATE);
outputStream.write(("Accelerometer (m/s2): " + "\nX" + " " + df.format(X11) + "\nY" + " " + df.format(X12) + "\nZ" + " " + df.format(X13)
).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
displayReading2.setText("Rotational Vector: " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X21=event.values[0];
float X22=event.values[1];
float X23=event.values[2];
if( flag) {
try {
outputStream=openFileOutput(file, Context.MODE_PRIVATE);
outputStream.write(("Rotational Vector : " +"\nX"+" " +df.format(X21) + "\nY"+" " + df.format(X22) + "\nZ"+" " + df.format(X23)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY)
displayReading3.setText("Gravity (m/s2): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
displayReading4.setText("Gyroscope (rad/s): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X31=event.values[0];
float X32=event.values[1];
float X33=event.values[2];
if( flag) {
try {
outputStream = openFileOutput(file, Context.MODE_PRIVATE);
outputStream.write(("Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33)
).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (!flag){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
It depends what file storage you are trying to access. I have used this for both Android and Android Wear. This accesses the app's Document Directory which is only accessible from the app and not by other apps. When I use this for internal storage will share that code as well.
This simply makes a toast showing all files in this directory one by one:
public void listFiles(View view) {
PackageManager m = getPackageManager();
String s = getPackageName();
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}
Context context = getApplicationContext();
File folder = new File(context.getFilesDir().toString());
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
Toast.makeText(MainActivity.this, "File " + listOfFiles[i].getName(),
Toast.LENGTH_SHORT).show();
//System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
Toast.makeText(MainActivity.this, "File " + listOfFiles[i].getName(),
Toast.LENGTH_SHORT).show();
//System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
This is also saving a file to the external storage of the watch that can be accessed with other apps:
private final String fileName = "aq.pcm";
private String TAGFILE = "ExternalFileWriteReadActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Enables Ambient mode.
mAmbientController = AmbientMode.attachAmbientSupport(this);
//Copy files
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File outFile = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES),
fileName);
if (!outFile.exists())
copyImageToMemory(outFile);
}
}
// Copy file methods
private void copyImageToMemory(File outFile) {
try {
BufferedOutputStream os = new BufferedOutputStream(
new FileOutputStream(outFile));
BufferedInputStream is = new BufferedInputStream(getResources()
.openRawResource(R.raw.sound));
copy(is, os);
} catch (FileNotFoundException e) {
Log.e(TAGFILE, "FileNotFoundException");
}
}
private void copy(InputStream is, OutputStream os) {
final byte[] buf = new byte[1024];
int numBytes;
try {
while (-1 != (numBytes = is.read(buf))) {
os.write(buf, 0, numBytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
Log.e(TAGFILE, "IOException");
}
}
}
i my PushSharp service is self hosted in windows service,
but after a short while it always throws:
Events_OnNotificationSendFailure
- the exception is "There were not enough free threads in the ThreadPool to complete the operation". what is the proper way to do that?
public partial class PushNotificationService : ServiceBase
{
private static bool flagNotification = true;
static PushService push;
protected override void OnStart(string[] args)
{
SetPushService();
//start console service worker
Thread t = new Thread(NotificationServiceWorker);
t.IsBackground = true;
t.Start();
}
private static void NotificationServiceWorker()
{
try
{
int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
while (flagNotification)
{
try
{
/// get IosPushNotificationService
IosPushNotificationService pns = new IosPushNotificationService();
/// Get The New Notification from db
List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();
if (notificationToSend != null && notificationToSend.Count > 0)
{
SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
}
Thread.Sleep(sendNotificationTimeGap);
}
catch (Exception ex)
{
CustomError.Error("error in flagNotification loop", ex);
}
}
}
catch (Exception ex)
{
CustomError.Error("error in NotificationServiceWorker", ex);
}
}
private static void SetPushService()
{
push = new PushService();
push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
string androidPackage = ConfigurationManager.AppSettings["androidPackage"];
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });
string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
var appleCert = File.ReadAllBytes(appleCertificates);
var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;
push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));
}
}
Don't use thread instead you can use timer like this
protected override void OnStart(string[] args)
{
NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);
if (oNotificationComponent ==null)
oNotificationComponent = new NotificationComponent();
Heading
try
{
if (StartAppleNotificationService())
StartTimer();
}
catch (Exception ex)
{
NotificationServiceEventLog.WriteEntry(ex.Message);
}
base.OnStart(args);
}
private bool StartAppleNotificationService() {
bool IsStarted = false;
try
{
if (oPushService == null)
oPushService = new PushService();
NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
var settings = new ApplePushChannelSettings(true, appleCert, "123456");
oPushService.StartApplePushService(settings);
IsStarted = true;
}
catch (Exception ex)
{
throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
}
return IsStarted;
}
private bool StartTimer() {
try
{
Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
MyTimer = new Timer();
MyTimer.Interval += (1)*(60)*(1000);
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
}
catch (Exception ex) {
throw ex;
}
return true;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
string SentNotificationIDz = "";
try
{
MyTimer.Enabled = false;
string szConnectionString = #"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin#321";
//ConfigurationManager.AppSettings["connString"];
lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);
foreach (NotificationModel oNotificationModel in lNotifictaion)
{
SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
if (SentNotificationIDz == null)
SentNotificationIDz += oNotificationModel.Oid;
else
SentNotificationIDz += "," + oNotificationModel.Oid;
}
oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
MyTimer.Enabled = true;
}
catch (Exception ex) {
throw ex;
}
//
}
private void SendNotification(string p_szDeviceToken,string p_szAlert)
{
try
{
oPushService.QueueNotification(NotificationFactory.Apple()
.ForDeviceToken(p_szDeviceToken)
.WithAlert(p_szAlert)
.WithBadge(2)
.WithSound("default")
.WithExpiry(DateTime.Now.AddDays(1))
);
}
catch (Exception ex)
{
throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
}
}
I don't know what is the problem, but SMS is not received with below code and when I see in the phone memory, app is invalid.
Can anyone correct this code?
I am having a lot of issues with this, it compiles well, but when it is on the real phone, the app says it is invalid,Nokia 2630 supports MIDP 2.0, so not a phone problem.
package Pushtest;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.GridLayout;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.util.Date;
import java.io.*;
/**
* #author test
*/
public class SendApprooval extends MIDlet implements Runnable, ActionListener, MessageListener {
Date todaydate;
private Dialog content, alert;
Thread thread;
String[] connections;
boolean done;
String senderAddress, mess;
MessageConnection smsconn = null, clientConn = null;
Message msg;
// public SendApprooval() {
/*
smsPort = getAppProperty("SMS-Port");
content = new Dialog("");
content.addComponent(new Label("Waiting for Authentication Request"));
content.setDialogType(Dialog.TYPE_INFO);
content.setTimeout(2000);
// exitCommand = new Command("Exit", Command.EXIT, 2);
// content.addCommand(exitCommand)
content.addCommand(exitCommand);
content.addCommandListener(this);
content.show();
} */
public void startApp() {
Display.init(this);
String smsConnection = "sms://:" + 5000;
if (smsconn == null) {
try {
smsconn = (MessageConnection) Connector.open(smsConnection);
smsconn.setMessageListener(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
connections = PushRegistry.listConnections(true);
if ((connections == null) || (connections.length == 0)) {
content.addComponent(new Label("Waiting for Authentication Request"));
}
done = false;
thread = new Thread(this);
thread.start();
// display.setCurrent(resumeScreen);
}
public void run() {
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
} catch (IOException e) {
content.addComponent(new Label(e.toString()));
Display.init(content);
}
}
public void pauseApp() {
done = true;
thread = null;
Display.init(this);
}
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
}
notifyDestroyed();
}
}
public void showMessage(String message, Display displayable) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setTitle("Error");
alert.addComponent(new Label(message));
alert.setDialogType(Dialog.TYPE_ERROR);
alert.setTimeout(5000);
alert.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
content.addComponent(new Label("Waiting for Authentication Request"));
content.setLayout(new GridLayout(5, 1));
content.setDialogType(Dialog.TYPE_INFO);
content.show();
done = false;
thread = new Thread(this);
thread.start();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int id = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdName1 = cmd.getCommandName();
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
if (("Exit").equals(cmdName1)) {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This may be cause because your sending SMS might not send on the port you defined in your code,
Please look at to this working example.
i found it guys, Thanks for your support, i'm sure i would come back with more queries, i have written a sample receiving sms code with port 5000, It would Help someone in someway,
Before you start,
Right click your application in netbeans and select properties. Now select the application descriptor. select the attribute tab and select the Add button. Give the following in the corresponding fields.
Name : SMS-Port
Value : portno
Now u have registered the port no successfully.
Now again select the push registry tab.
give the following in the corresponding fields.
Class Name : Package name.class name
Sender ip : *
Connection String: sms://:portno
Now u have registered the push registry successfully.
CODE HERE:
public class SMSReceiver extends MIDlet implements ActionListener, MessageListener {
private Form formReceiver;
private TextField tfPort;
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/m21.res");
UIManager.getInstance().setThemeProps(
r.getTheme(r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
e.printStackTrace();
}
formReceiver = new Form();
formReceiver.setTitle(" ");
formReceiver.setLayout(new GridLayout(4, 2));
formReceiver.setTransitionInAnimator(null);
TextField.setReplaceMenuDefault(false);
Label lblPort = new Label("Port");
tfPort = new TextField();
tfPort.setMaxSize(8);
tfPort.setUseSoftkeys(false);
tfPort.setHeight(10);
tfPort.setConstraint(TextField.DECIMAL);
formReceiver.addComponent(lblPort);
formReceiver.addComponent(tfPort);
formReceiver.addCommand(new Command("Listen"), 0);
formReceiver.addCommand(new Command("Exit"), 0);
formReceiver.addCommandListener(this);
formReceiver.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.addComponent(new Label("Message received : "+tMessage.getPayloadText()+"\n"));
} else {
formReceiver.addComponent(new Label("Unknown Message received\n"));
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int idi = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdNam = cmd.getCommandName();
if ("Listen".equals(cmdNam)) {
ListenSMS sms = new ListenSMS(tfPort.getSelectCommandText(), this);
sms.start();
}
if ("Exit".equals(cmdNam)) {
notifyDestroyed();
}
}
}
class ListenSMS extends Thread {
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
public ListenSMS(String port, MessageListener listener) {
this.port = port;
this.Listener = listener;
}
public void run() {
try {
msgConnection = (MessageConnection)Connector.open("sms://:" + 5000);
msgConnection.setMessageListener(Listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}