I need some help!
I need to send some NMEA data from device via COM port to USB port on my Android tablet. When I connect my silab CP210x UART Bridge to tablet, it automaticly launches my programm, but when I try to send some data, my programm does not see it. I'm using usb-serial-for-android library ( https://github.com/mik3y/usb-serial-for-android ). I followed all the instructions from github.
Here is my code:
package com.example.simplexyplotactivity;
import java.io.IOException;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PointF;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.EventLog;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import com.androidplot.Plot;
import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class Simple_xy_plot_example extends Activity implements OnTouchListener {
private int com_cnt;
private String buf;
private String[] fields;
private int buf_max_length;
private int buf_idx;
private boolean buf_started;
public float course=0;
SoundPool sound_pool;
int rot_sound_ID;
private static final String ACTION_USB_PERMISSION ="com.prolific.pl2303hxdsimpletest.USB_PERMISSION";
private static final int SERIES_SIZE = 200;
private XYPlot plotOne;
private SimpleXYSeries series1 = null;
private PointF minXY;
private PointF maxXY;
NMEA_Receiver data;
private Thread myThread;
private String str;
private String stroka;
float zoomRatio = 2, leftBoundary, rightBoundary;
USB2ComDetector mUSB2ComDetector;
Handler CBhandler;
private UsbManager usb_manager;
private static UsbSerialPort ser_port = null;
ComponentName service_name;
byte temp_buf[]=new byte[4096];
private class MyPlotUpdater implements Observer {
Plot plot;
public MyPlotUpdater(Plot plot) {
this.plot = plot;
}
#Override
public void update(Observable o, Object arg) {
plot.redraw();
}
}
private boolean USB2ComConnect() {
/*if (ser_port != null) return false;
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
if (availableDrivers.isEmpty()) {
} else {
// open connection to first avail. driver
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = usb_manager.openDevice(driver.getDevice());
if (connection == null) {
} else { // Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
byte temp_buf[]=new byte[4096]; // 1 byte per pressure sensor, plus 2 bytes for carriage return
int numBytesRead = port.read(temp_buf, 1000);
String arduinoData = new String(temp_buf, "US-ASCII");
Toast.makeText(getApplicationContext(), arduinoData, Toast.LENGTH_SHORT).show(); // Toast debugging
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: couldn't read data from USB device", Toast.LENGTH_LONG).show(); // Toast debugging
}
}
}
/* List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
ser_port=ports.get(0);
UsbDeviceConnection connection=usb_manager.openDevice(ser_port.getDriver().getDevice());
try {
ser_port.open(connection);
ser_port.setParameters(4800, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
ser_port.purgeHwBuffers(true, true);
} catch (IOException e) {
Log.e("NMEAParser", "Cant open or set parameter to serial port");
e.printStackTrace();
return true;
}*/
return false;
}
//**********
public boolean IsCOMopened(){return ser_port!=null?true:false;}
private MyPlotUpdater plotUpdater;
public void onResume() {
// kick off the data generating thread:
myThread = new Thread(data);
myThread.start();
super.onResume();
// try {
// data.EnableRec(true);
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
public void stopThread() {
keepRunning = false;
}
#Override
public void onPause() {
// data.stopThread();
super.onPause();
}
private boolean keepRunning = false;
class NMEA_Receiver implements Runnable {
private static final int SAMPLE_SIZE = 30;
public int k = 1;
private int kk = 1;
private UsbSerialDriver driver;
private boolean rec_enabled=false;//enable/disable when cable plug in/off
private boolean rec_alive=true;//to terminate thread when stop app
byte rec_buf[]=new byte[256];
boolean rec_started=false;
boolean trans_started;
private boolean buf_started;
private String buf;
int rec_idx=0;
NMEA_Receiver(UsbSerialDriver driver){
this.driver=driver;
}
public void stopThread() {
keepRunning = false;
}
synchronized private void SuspendRec(){
}
synchronized public void EnableRec(boolean en) throws IOException {
rec_enabled = en;
UsbDevice dev;
if (en) {
try {
//driver.open();
//driver.setBaudRate(4800);
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
//driver.close();
}
}
// ***********************************************************************************
// ***********************************************************************************
String GetRecBuf(){
return new String(rec_buf);
}
// ***********************************************************************************
public int Transmit(String tr_buf){
return 1;
}
// ***********************************************************************************
public boolean IsCOMMConnected(){
// return mPL2303.isConnected();
return false;
}
public void run() {
//byte temp_buf[]=new byte[4096];
int yy1;
int yy2;
int yy3;
int yy4;
int yy5;
int i=0;
int length=0;
try {
length=ser_port.read(temp_buf, 1000);
} catch (Exception e) {
e.printStackTrace();
}
String str2;
String str3, str4, str5;
boolean terminate=false;
keepRunning = true;
while (keepRunning) {
str5=temp_buf.toString();
Toast toast = Toast.makeText(getApplicationContext(),
str5, Toast.LENGTH_SHORT);
toast.show();
for(int k=0;k<length;k++){
if (temp_buf[0]=='$') {
buf_started = true;
}
if(buf_started){
buf+=(char)temp_buf[k];
if(temp_buf[k]=='\n'){
str = buf;
yy1 = Character.getNumericValue(str.charAt(7));
if (str.charAt(8) == '.') {
str3 = String.valueOf(str.charAt(8));
str2 = "" + yy1 + str3;
} else {
yy2 = Character.getNumericValue(str.charAt(8));
str2 = "" + yy1 + yy2;
}
if (str.charAt(9) == '.') {
str4 = String.valueOf(str.charAt(9));
str2 = str2 + str4;
} else {
if ((str.charAt(9) >= '0' && str.charAt(9) <= '9')) {
yy3 = Character.getNumericValue(str.charAt(9));
str2 = str2 + yy3;
}
}
if (str.charAt(10) == '.') {
str4 = String.valueOf(str.charAt(10));
str2 = str2 + str4;
} else if ((str.charAt(10) >= '0' && str.charAt(10) <= '9')) {
yy4 = Character.getNumericValue(str.charAt(10));
str2 = str2 + yy4;
}
if ((str.charAt(11) >= '0' && str.charAt(11) <= '9')) {
yy5 = Character.getNumericValue(str.charAt(11));
str2 = str2 + yy5;
}
course = Float.parseFloat(str2); //добавить необходимое число
kk++;
series1.addLast(kk, course);
plotOne.setRangeLabel(String.valueOf(course));
plotOne.redraw();// для выведения глубины
}
}
}
}
}
public Number getY(int series, int max) {
return 1;
}
}
public class USB2ComDetector extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
//try {
//data.EnableRec(false);
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_xy_plot_example);
// USB2ComConnect();
// try{
// USB2ComConnect();}
// catch (NullPointerException e){
// e.printStackTrace();
// }
// UsbManager usb_mngr=(UsbManager)getSystemService(Context.USB_SERVICE);
// List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_mngr);
//if(availableDrivers.isEmpty()==false){
// List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
// UsbDeviceConnection connection=usb_mngr.openDevice(ports.get(0).getDriver().getDevice());
// }
//
//UsbSerialDriver driver = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
//data = new NMEA_Receiver();
try {
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.isEmpty()){
Toast toast = Toast.makeText(getApplicationContext(),
"FAIL", Toast.LENGTH_SHORT);
toast.show();
}
//try {
// data.EnableRec(true);
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
return;
}
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
return;
}
// Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1,UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error: couldn't read data from USB device",Toast.LENGTH_LONG).show(); // Toast debugging
}
mUSB2ComDetector=new USB2ComDetector();
IntentFilter filter=new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUSB2ComDetector,filter);
sound_pool=new SoundPool(1, AudioManager.STREAM_MUSIC,0);
rot_sound_ID=sound_pool.load("/system/media/audio/ui/VideoRecord.ogg",1 );
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//plot setup
plotOne = (XYPlot) findViewById(R.id.myFirstXYPlot);
plotOne.setOnTouchListener(this);
plotOne.getGraphWidget().setTicksPerRangeLabel(2);
plotOne.getGraphWidget().setTicksPerDomainLabel(2);
plotOne.getGraphWidget().setRangeLabelWidth(25);
//plotOne.setRangeLabel("");
plotOne.setDomainLabel("");
plotOne.setBorderStyle(Plot.BorderStyle.NONE, null, null);
plotOne.getLayoutManager().remove(plotOne.getLegendWidget());
plotOne.getGraphWidget().setSize(new SizeMetrics(0,SizeLayoutType.FILL,
0, SizeLayoutType.FILL));
plotOne.setPlotMargins(0,0,0,0);
//********
//series setup
series1 = new SimpleXYSeries("PARAM");
series1.useImplicitXVals();
LineAndPointFormatter line1 = new LineAndPointFormatter();
line1.setPointLabelFormatter(new PointLabelFormatter());
plotOne.addSeries(series1, line1);
plotOne.redraw();
plotOne.calculateMinMaxVals();
minXY = new PointF(plotOne.getCalculatedMinX().floatValue(),
plotOne.getCalculatedMinY().floatValue());
maxXY = new PointF(plotOne.getCalculatedMaxX().floatValue(),
plotOne.getCalculatedMaxY().floatValue());
leftBoundary = series1.getX(0).floatValue();
rightBoundary = series1.getX(series1.size() - 1).floatValue();
}
//*****************
// Definition of the touch states
static final int NONE = 0;
static final int ONE_FINGER_DRAG = 1;
static final int TWO_FINGERS_DRAG = 2;
int mode = NONE;
PointF firstFinger;
float distBetweenFingers;
boolean stopThread = false;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // Start gesture
firstFinger = new PointF(event.getX(), event.getY());
mode = ONE_FINGER_DRAG;
stopThread = true;
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger
distBetweenFingers = spacing(event);
// the distance check is done to avoid false alarms
if (distBetweenFingers > 5f) {
mode = TWO_FINGERS_DRAG;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ONE_FINGER_DRAG) {
PointF oldFirstFinger = firstFinger;
firstFinger = new PointF(event.getX(), event.getY());
scroll(oldFirstFinger.x - firstFinger.x);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
} else if (mode == TWO_FINGERS_DRAG) {
float oldDist = distBetweenFingers;
distBetweenFingers = spacing(event);
zoom(oldDist / distBetweenFingers);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
}
break;
}
return true;
}
private void zoom(float scale) {
float domainSpan = maxXY.x - minXY.x;
float oldMax = maxXY.x;
float oldMin = minXY.x;
float domainMidPoint = maxXY.x - (domainSpan / 2.0f);
float offset = domainSpan * scale / 2.0f;
minXY.x = domainMidPoint - offset;
maxXY.x = domainMidPoint + offset;
float newSpan = maxXY.x - minXY.x;
if (newSpan < (float)5) {
minXY.x = oldMin;
maxXY.x = oldMax;
}
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan * zoomRatio;
if (maxXY.x > series1.getX(series1.size() - 1).floatValue())
maxXY.x = rightBoundary;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan * zoomRatio;
if (minXY.x < leftBoundary) minXY.x = leftBoundary;
}
}
private void scroll(float pan) {
float domainSpan = maxXY.x - minXY.x;
float step = domainSpan / plotOne.getWidth();
float offset = pan * step;
minXY.x = minXY.x + offset;
maxXY.x = maxXY.x + offset;
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan;
}
}
private float spacing(MotionEvent
event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
}
I suffer similar problems to yours when using the library usb-serial-for-android. I write bytes to the serial port but my Arduino could not get any signal. After a while I discovered the AndroidApp DroidTerm can do what I want straightforwardly. It uses https://github.com/felHR85/UsbSerial as the serial port driver library for DroidTerm. I discovered that this library supports the Silicon Lab CP21xx UART and some more:
..Devices supported Currently UsbSerial supports three of the most used
USB to serial chipsets:
– FTDI FT232 (I am not going to brick your device, trust me :))
– Silicon Labs CP210x
– Prolific PL2303HX (at least HX version)
– CH340/CH341..
So it may solve your problem.
Related
How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
I try to inject some keys in a text field with a InputMethodService.
In my Manifest everything seems alright.
Everytime when I call getCurrentInputConnection() I get null.
My class extends InputMethodService and I start the service.
Can anyone help me? Is there something else I need to do to get the currentInputConnection??
Here is the code:
Its from an open source project called WifiKeyboard
And I try to inject code with the function setText(String text)
package com.example.twolibs;
/**
* WiFi Keyboard - Remote Keyboard for Android.
* Copyright (C) 2011 Ivan Volosyuk
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.util.HashSet;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.input.InputManager;
import android.inputmethodservice.InputMethodService;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethod;
public class WiFiInputMethod extends InputMethodService {
public static final int KEY_HOME = -1000;
public static final int KEY_END = -1001;
public static final int KEY_CONTROL = -1002;
public static final int KEY_DEL = -1003;
#Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
super.onStartInput(attribute, restarting);
// boolean multiline = (attribute.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0;
// Log.d("ivan", "onStartInput "
// + "actionId=" + attribute.actionId + " "
// + "id=" + attribute.fieldId + " "
// + "name=" + attribute.fieldName + " "
// + "opt=" + Integer.toHexString(attribute.imeOptions) + " "
// + "inputType=" + Integer.toHexString(attribute.inputType) + " "
// + "priv=" + attribute.privateImeOptions
// + "multiline=" + multiline);
try {
String text = getText();
} catch (NullPointerException e) {
}
}
ServiceConnection serviceConnection;
#Override
public void onDestroy() {
// Debug.d("WiFiInputMethod onDestroy()");
if (serviceConnection != null)
unbindService(serviceConnection);
serviceConnection = null;
super.onDestroy();
}
PowerManager.WakeLock wakeLock;
HashSet<Integer> pressedKeys = new HashSet<Integer>();
#Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "wifikeyboard");
// Debug.d("WiFiInputMethod started");
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
// Debug.d("WiFiInputMethod connected to HttpService.");
}
//#Override
public void onServiceDisconnected(ComponentName name) {
// Debug.d("WiFiInputMethod disconnected from HttpService.");
}
};
}
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
void receivedChar(int code) {
wakeLock.acquire();
wakeLock.release();
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case 'a':case 'A': selectAll(conn); return;
case 'x':case 'X': cut(conn); return;
case 'c':case 'C': copy(conn); return;
case 'v':case 'V': paste(conn); return;
}
}
String text = null;
if (code >= 0 && code <= 65535) {
text = new String(new char[] { (char) code } );
} else {
int HI_SURROGATE_START = 0xD800;
int LO_SURROGATE_START = 0xDC00;
int hi = ((code >> 10) & 0x3FF) - 0x040 | HI_SURROGATE_START;
int lo = LO_SURROGATE_START | (code & 0x3FF);
text = new String(new char[] { (char) hi, (char) lo } );
}
conn.commitText(text, 1);
}
#SuppressWarnings("unused")
void receivedKey(int code, boolean pressed) {
if (false) {
for (int key : pressedKeys) {
sendKey(key, false, false);
}
pressedKeys.clear();
resetModifiers();
return;
}
if (pressedKeys.contains(code) == pressed) {
if (pressed == false) return;
// ignore autorepeat on following keys
switch (code) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MENU: return;
}
}
if (pressed) {
pressedKeys.add(code);
System.out.println("one");
sendKey(code, pressed, false);
} else {
pressedKeys.remove(code);
sendKey(code, pressed, pressedKeys.isEmpty());
}
}
void resetModifiers() {
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
return;
}
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
private long lastWake;
void sendKey(int code, boolean down, boolean resetModifiers) {
System.out.println("two");
/*
long time = System.currentTimeMillis();
if (time - lastWake > 5000) {
wakeLock.acquire();
wakeLock.release();
lastWake = time;
}
*/
InputConnection conn = getCurrentInputConnection();
System.out.println("three");
if (conn == null) {
System.out.println("kacke");
// Debug.d("connection closed");
return;
}
if (code < 0) {
if (down == false) return;
switch (code) {
case KEY_HOME: keyHome(conn); break;
case KEY_END: keyEnd(conn); break;
case KEY_DEL: keyDel(conn); break;
}
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!down) return;
wordLeft(conn);
return;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!down) return;
wordRight(conn);
return;
case KeyEvent.KEYCODE_DEL:
if (!down) return;
deleteWordLeft(conn);
return;
case KeyEvent.KEYCODE_FORWARD_DEL:
deleteWordRight(conn);
return;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
copy(conn);
return;
}
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
paste(conn);
return;
}
}
if (code == KeyEvent.KEYCODE_ENTER) {
if (shouldSend()) {
if (!down) return;
Log.d("ivan", "sending submit action");
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
return;
}
}
// if (pressedKeys.contains(KEY_CONTROL)) {
// if (down == false) return;
// switch (code) {
// case KeyEvent.KEYCODE_A: selectAll(conn); break;
// case KeyEvent.KEYCODE_X: cut(conn); break;
// case KeyEvent.KEYCODE_C: copy(conn); break;
// case KeyEvent.KEYCODE_V: paste(conn); break;
// }
// return;
// }
System.out.println("four");
conn.sendKeyEvent(new KeyEvent(
android.os.SystemClock.uptimeMillis(),
android.os.SystemClock.uptimeMillis(),
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code,
0,
(pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)
? KeyEvent.META_SHIFT_LEFT_ON : 0) +
(pressedKeys.contains(KEY_CONTROL)? KeyEvent.META_CTRL_ON : 0) +
(pressedKeys.contains(KeyEvent.KEYCODE_ALT_LEFT)
? KeyEvent.META_ALT_LEFT_ON : 0)
));
if (resetModifiers) {
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
}
private boolean shouldSend() {
if (pressedKeys.contains(KEY_CONTROL)) {
// Log.d("ivan", "Control pressed");
return true;
}
EditorInfo editorInfo = getCurrentInputEditorInfo();
if (editorInfo == null) {
// Log.d("ivan", "No editor info");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_CLASS_TEXT) == 0) {
// Log.d("ivan", "Not text, sending enter");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0) {
// Log.d("ivan", "Multi-line, sending ordinary enter");
return false;
}
int action = editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
if (action == EditorInfo.IME_ACTION_NONE || action == EditorInfo.IME_ACTION_DONE) {
// Log.d("ivan", "No useful action, sending enter");
return false;
}
// Log.d("ivan", "Useful action to be performed");
return true;
}
private void keyDel(InputConnection conn) {
// if control key used -- delete word right
if (pressedKeys.contains(KEY_CONTROL)) {
deleteWordRight(conn);
return;
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
cut(conn);
return;
}
conn.deleteSurroundingText(0, 1);
conn.commitText("", 0);
}
private void paste(InputConnection conn) {
conn.performContextMenuAction(android.R.id.paste);
}
private void copy(InputConnection conn) {
conn.performContextMenuAction(android.R.id.copy);
}
private void cut(InputConnection conn) {
conn.performContextMenuAction(android.R.id.cut);
}
public void selectAll(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
try {
conn.setSelection(0, text.text.length());
} catch (NullPointerException e) {
// Potentially, text or text.text can be null
}
}
ExtractedTextRequest req = new ExtractedTextRequest();
{
req.hintMaxChars = 100000;
req.hintMaxLines = 10000;
}
private void deleteWordRight(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
conn.deleteSurroundingText(0, end - text.selectionEnd);
}
private void deleteWordLeft(InputConnection conn) {
// TODO: what is the correct word deleting policy?
// delete until next space? until next different character type?
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
conn.deleteSurroundingText(text.selectionEnd - end, 0);
}
private void wordRight(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void wordLeft(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyEnd(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = text.text.length();
} else {
end = text.text.toString().indexOf('\n', text.selectionEnd);
if (end == -1) end = text.text.length();
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyHome(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = 0;
} else {
end = text.text.toString().lastIndexOf('\n', text.selectionEnd - 1);
end++;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
boolean setText(String text) {
// FIXME: need feedback if the input was lost
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return false;
}
conn.commitText(text, text.length());
conn.beginBatchEdit();
// FIXME: hack
conn.deleteSurroundingText(100000, 100000);
conn.commitText(text, text.length());
conn.endBatchEdit();
return true;
}
String getText() {
String text = "";
try {
InputConnection conn = getCurrentInputConnection();
ExtractedTextRequest req = new ExtractedTextRequest();
req.hintMaxChars = 1000000;
req.hintMaxLines = 10000;
req.flags = 0;
req.token = 1;
text = conn.getExtractedText(req, 0).text.toString();
} catch (Throwable t) {
}
return text;
}
}
Thank you
I have this code for compressing pictures , I have two error , I have separated these errors with line in code like this (...........) first is : The left-hand side of an assignment must be a variable .......... and the second is Type mismatch: cannot convert from Object to String ................. how can I fix them ???
package com.example.resizingimages;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
public class GetImageActivity extends Activity
implements MediaScannerConnection.MediaScannerConnectionClient, DialogInterface
{
private static final int CAMERA_REQUEST = 1800;
private static final int GALLERY_KITKAT_INTENT_CALLED = 1500;
private static final int SELECT_PICTURE = 1;
static String filePath;
private TextView Name;
private TextView Size;
MediaScannerConnection conn;
File file;
private String filename;
private int height;
Uri imageUri;
private ImageView img;
private Uri outputFileUri;
Uri outputFileUri1;
String path1;
private String path2;
private Bitmap picture;
private File root;
File sdImageMainDirectory;
private Uri selectedImageUri;
private int width;
private void cameraaa(String paramString, Uri paramUri)
{
while (true)
{
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inSampleSize = 2;
localOptions.inPurgeable = true;
byte[] arrayOfByte = new byte[1024];
localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions.inTempStorage = arrayOfByte;
this.picture = BitmapFactory.decodeStream(localInputStream, null, localOptions);
switch (new ExifInterface(paramString).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str = sizee(paramUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str, 0).show();
System.out.println("Image Path : " + paramString);
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
}
public static String getDataColumn(Context paramContext, Uri paramUri, String paramString, String[] paramArrayOfString)
{
Cursor localCursor = null;
String[] arrayOfString = { "_data" };
try
{
localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, paramString, paramArrayOfString, null);
if ((localCursor != null) && (localCursor.moveToFirst()))
{
String str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
return str;
}
}
finally
{
if (localCursor != null)
localCursor.close();
}
if (localCursor != null)
localCursor.close();
return null;
}
public static String getPathl(Context paramContext, Uri paramUri)
{
int i;
if (Build.VERSION.SDK_INT >= 19)
i = 1;
while ((i != 0) && (DocumentsContract.isDocumentUri(paramContext, paramUri)))
if (isExternalStorageDocument(paramUri))
{
String[] arrayOfString3 = DocumentsContract.getDocumentId(paramUri).split(":");
if (!"primary".equalsIgnoreCase(arrayOfString3[0]))
break label271;
return Environment.getExternalStorageDirectory() + "/" + arrayOfString3[1];
i = 0;
}
else
{
if (isDownloadsDocument(paramUri))
{
String str2 = DocumentsContract.getDocumentId(paramUri);
return getDataColumn(paramContext, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(str2).longValue()), null, null);
}
if (!isMediaDocument(paramUri))
break label271;
String[] arrayOfString1 = DocumentsContract.getDocumentId(paramUri).split(":");
String str1 = arrayOfString1[0];
Uri localUri;
if ("image".equals(str1))
localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
while (true)
{
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = arrayOfString1[1];
return getDataColumn(paramContext, localUri, "_id=?", arrayOfString2);
if ("video".equals(str1))
{
localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else
{
boolean bool = "audio".equals(str1);
localUri = null;
if (bool)
localUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
}
if ("content".equalsIgnoreCase(paramUri.getScheme()))
return getDataColumn(paramContext, paramUri, null, null);
if ("file".equalsIgnoreCase(paramUri.getScheme()))
return paramUri.getPath();
label271: return filePath;
}
public static boolean isDownloadsDocument(Uri paramUri)
{
return "com.android.providers.downloads.documents".equals(paramUri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri paramUri)
{
return "com.android.externalstorage.documents".equals(paramUri.getAuthority());
}
public static boolean isMediaDocument(Uri paramUri)
{
return "com.android.providers.media.documents".equals(paramUri.getAuthority());
}
private void openAddPhoto()
{
String[] arrayOfString = { "Camera", "Gallery" };
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle(getResources().getString(2130968578));
localBuilder.setItems(arrayOfString, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
if (paramAnonymousInt == 0)
{
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", "new-photo-name.jpg");
localContentValues.put("description", "Image capture by camera");
GetImageActivity.this.imageUri = GetImageActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);
Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
localIntent1.putExtra("output", GetImageActivity.this.imageUri);
GetImageActivity.this.startActivityForResult(localIntent1, 1800);
}
if (paramAnonymousInt == 1)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent localIntent2 = new Intent();
localIntent2.setType("image/*");
localIntent2.setAction("android.intent.action.GET_CONTENT");
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent2, "Select Picture"), 1);
}
}
else
return;
Intent localIntent3 = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent3, "Select Picture"), 1500);
}
});
localBuilder.setNeutralButton("cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
private void startScan()
{
if (this.conn != null)
this.conn.disconnect();
this.conn = new MediaScannerConnection(this, this);
this.conn.connect();
}
public void cancel()
{
}
public void dismiss()
{
}
public String getPath(Uri paramUri)
{
Cursor localCursor = managedQuery(paramUri, new String[] { "_data" }, null, null, null);
String str = null;
if (localCursor != null)
{
int i = localCursor.getColumnIndexOrThrow("_data");
localCursor.moveToFirst();
str = localCursor.getString(i);
}
return str;
}
public String name(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
this.filename = filePath.substring(i + 1, paramString.length());
return this.filename;
}
if (paramString.charAt(j) == '/')
i = j;
}
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt2 == -1)
{
if (paramInt1 == 1)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
Toast.makeText(getApplicationContext(), "DATA " + filePath, 0).show();
filePath = getPath(this.selectedImageUri);
InputStream localInputStream2 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
localOptions2.inSampleSize = 2;
localOptions2.inPurgeable = true;
byte[] arrayOfByte2 = new byte[1024];
localOptions2.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions2.inTempStorage = arrayOfByte2;
this.picture = BitmapFactory.decodeStream(localInputStream2, null, localOptions2);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str4 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str4, 0).show();
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException3)
{
Toast.makeText(getApplicationContext(), "Error " + localException3.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
if (paramInt1 == 1500)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
getPathl(getApplicationContext(), this.selectedImageUri);
getContentResolver();
filePath = getPathl(getApplicationContext(), this.selectedImageUri);
InputStream localInputStream1 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
localOptions1.inSampleSize = 2;
localOptions1.inPurgeable = true;
byte[] arrayOfByte1 = new byte[1024];
localOptions1.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions1.inTempStorage = arrayOfByte1;
this.picture = BitmapFactory.decodeStream(localInputStream1, null, localOptions1);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str3 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str3, 0).show();
return;
case 6:
case 3:
}
}
catch (Exception localException2)
{
Toast.makeText(getApplicationContext(), "Error " + localException2.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 90);
continue;
rotateImage(this.picture, 180);
}
if (paramInt1 == 1800)
{
filePath = null;
this.selectedImageUri = this.imageUri;
if (this.selectedImageUri != null)
while (true)
{
String str1;
try
{
str1 = this.selectedImageUri.getPath();
String str2 = getPath(this.selectedImageUri);
if (str2 != null)
{
filePath = str2;
if (filePath == null)
break;
Toast.makeText(getApplicationContext(), " path" + filePath, 1).show();
new Intent(getApplicationContext(), GetImageActivity.class);
cameraaa(filePath, this.selectedImageUri);
return;
}
}
catch (Exception localException1)
{
Toast.makeText(getApplicationContext(), "Internal error", 1).show();
Log.e(localException1.getClass().getName(), localException1.getMessage(), localException1);
return;
}
if (str1 != null)
{
filePath = str1;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path", 1).show();
Log.e("Bitmap", "Unknown path");
}
}
}
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
setContentView(2130903040);
Display localDisplay = getWindowManager().getDefaultDisplay();
this.width = localDisplay.getWidth();
this.height = localDisplay.getHeight();
final Button localButton = (Button)findViewById(2131296257);
final Spinner localSpinner = (Spinner)findViewById(2131296260);
final TextView localTextView = (TextView)findViewById(2131296259);
localButton.setVisibility(4);
localSpinner.setVisibility(4);
localTextView.setVisibility(4);
if (this.height <= 480)
{
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 20 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -20 + (this.height - this.height / 3)));
localTextView.setText("Image Quality");
localTextView.setText("Image Quality");
this.img = ((ImageView)findViewById(2131296258));
this.img.setBackgroundResource(2130837504);
//first error is here
.......................................................................................
***(-160 + this.height);***
(-160 + this.height);
((int)(0.8D * this.width));
AbsoluteLayout.LayoutParams localLayoutParams1 = new AbsoluteLayout.LayoutParams((int)(0.8D * this.width), (int)(0.5D * this.height), (int)(this.width - 0.9D * this.width), (int)(this.height - 0.9D * this.height));
this.img.setLayoutParams(localLayoutParams1);
ImageView localImageView = this.img;
View.OnClickListener local1 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
GetImageActivity.this.img.setImageDrawable(null);
GetImageActivity.this.img.setBackgroundResource(2130837504);
localButton.setVisibility(0);
localSpinner.setVisibility(0);
localTextView.setVisibility(0);
GetImageActivity.this.openAddPhoto();
}
};
localImageView.setOnClickListener(local1);
if (this.height > 480)
break label505;
localButton.setBackgroundResource(2130837507);
(-160 + this.height);
}
for (AbsoluteLayout.LayoutParams localLayoutParams2 = new AbsoluteLayout.LayoutParams(50, 50, -25 + this.width / 2, -51 + this.height); ; localLayoutParams2 = new AbsoluteLayout.LayoutParams(170, 170, -85 + this.width / 2, -170 + this.height))
{
localButton.setLayoutParams(localLayoutParams2);
View.OnClickListener local2 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
}
};
localButton.setOnClickListener(local2);
return;
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 30 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -10 + (this.height - this.height / 3)));
break;
label505: localButton.setBackgroundResource(2130837506);
(-160 + this.height);
}
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(2131230720, paramMenu);
return true;
}
public void onMediaScannerConnected()
{
try
{
this.conn.scanFile(filePath, "image/*");
return;
}
catch (IllegalStateException localIllegalStateException)
{
}
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == 2131296262)
shareagain();
while (true)
{
return true;
if (paramMenuItem.getItemId() == 2131296263)
try
{
startActivity(new Intent(this, readddme.class));
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
}
else if (paramMenuItem.getItemId() == 2131296264)
System.exit(0);
}
}
public void onScanCompleted(String paramString, Uri paramUri)
{
this.conn.disconnect();
}
public void rotateImage(Bitmap paramBitmap, int paramInt)
{
Matrix localMatrix = new Matrix();
localMatrix.setRotate(paramInt);
this.picture = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
}
public void share()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.SUBJECT", "#RABIDO");
localIntent.putExtra("android.intent.extra.TEXT", "#RABIDO");
localIntent.setType("image/*");
localIntent.putExtra("android.intent.extra.STREAM", this.selectedImageUri);
startActivity(Intent.createChooser(localIntent, "Share Image"));
}
public void shareagain()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "Check out 'RABIDO' - https://play.google.com/store/apps/details?id=decrease.image.uploader");
startActivity(Intent.createChooser(localIntent, "Share via"));
}
public String sizee(Uri paramUri)
{
Object localObject;
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
byte[] arrayOfByte = new byte[1024];
int i = 0;
float f;
while (true)
{
if (localInputStream.read(arrayOfByte) == -1)
{
f = i / 1000;
if (f >= 1000.0F)
break;
localObject = " " + i / 1000 + " KB";
break label164;
}
i += arrayOfByte.length;
}
String str = " " + f / 1000.0F + " MB";
localObject = str;
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error 5 " + localException.getMessage(), 0).show();
return "";
}
//second is here
..................................................................
label164: return localObject;
}
}
For the First error can you try something like this:
(this.height = this.height - 160);
The error indicates you are trying to make an assignment operation but you have not put a variable in the left hand side of the equation.
there may also be a short hand way to do this such as:
(this.height =- 160);
for the second error is seems that you have declared "localObject" as an Object.
can you just declare it as a String. seems that you are assigning a string to it and then wanting to return a string. See if that works.
i have a problem in this application(Mini4WD Lap Timer) in my Motorola Defy.. they provide they source code.. maybe you could help me to be compatible it on my device..
https://play.google.com/store/apps/details?id=com.pimentoso.android.laptimer&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5waW1lbnRvc28uYW5kcm9pZC5sYXB0aW1lciJd
the problem is when calibrating, it stock..
and the small preview in the upper-left of the timer is not working, only shows black..
here is the codes
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pimentoso.android.laptimer" android:versionCode="8"
android:versionName="1.4.1" android:installLocation="auto">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".TimerActivity" android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SensitivityDialogActivity"
android:label="#string/label_sensitivity" android:theme="#android:style/Theme.Dialog" />
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.SET_ORIENTATION" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
</manifest>
FPSCounter.java
package com.pimentoso.android.laptimer;
import android.util.Log;
public class FPSCounter {
long startTime = System.nanoTime();
int frames = 0;
public void logFrame() {
frames++;
if(System.nanoTime() - startTime >= 1000000000) {
Log.d("FPSCounter", "fps: " + frames);
frames = 0;
startTime = System.nanoTime();
}
}
}
SensitivityDialogActivity.java
package com.pimentoso.android.laptimer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SensitivityDialogActivity extends Activity implements OnClickListener, OnSeekBarChangeListener
{
private SeekBar bar;
private TextView barValue;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sensitivity);
findViewById(R.id.button_sensitivity_close).setOnClickListener(this);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
String currentValue = getPreferences(MODE_PRIVATE).getString("sensitivity", "15");
bar = (SeekBar) findViewById(R.id.seekbar_sensitivity);
bar.setOnSeekBarChangeListener(this);
barValue = (TextView) findViewById(R.id.seekbar_sensitivity_value);
barValue.setText(currentValue);
bar.setProgress(Integer.valueOf(currentValue));
// settare il valore nel timer a (25-barValue)
// barra 20 = 5
// barra 15 = 10
// barra 10 = 15
// barra 5 = 20
// barra 0 = 25
}
#Override
public void onClick(View v)
{
String finalValue = barValue.getText().toString();
getPreferences(MODE_PRIVATE).edit().putString("sensitivity", finalValue).commit();
TimerActivity.calibrateThreshold = 25 - Integer.valueOf(finalValue);
this.finish();
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{
String t = String.valueOf(arg1);
barValue.setText(t);
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
}
TimerActivity.java
package com.pimentoso.android.laptimer;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TimerActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback, OnClickListener {
// elementi del layout
SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
Camera mCamera;
TextView timerLabel;
TextView statusLabel;
TextView lap1Label;
TextView lap2Label;
TextView lap3Label;
TextView lapBestLabel;
Button startButton;
// flags
boolean isPreviewRunning = false;
boolean isCalibrating = false;
boolean isCalibrated = false;
boolean isStarted = false;
boolean isTimerRunning = false;
boolean caughtPreviousFrame = false;
// contatore dei frame per calibrazione
int frame = 0;
// offset dei pixel da controllare
int[] pixelOffset = new int[3];
// array di calibrazione
int[][] calibrateRange = new int[3][20];
// valori finali di calibrazione
int[] calibrateValue = new int[3];
// soglia di differenza di luminosità per catchare il frame
public static int calibrateThreshold = 10;
// tempo iniziale
long mStartTime = 0L;
// millisecondi di ultimo catch
long mLastCatchTime = 0;
// tempo del giro migliore
long bestLap = 0;
// tempi dei giri
// long[] laps = new long[3];
ArrayList<Long> laps = new ArrayList<Long>();
// contatore dei giri
int lapCount = 0;
FPSCounter fps = new FPSCounter();
Handler mHandler = new Handler();
StringBuffer timerBuffer;
StringBuffer lapBuffer;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis() - mStartTime;
timerLabel.setText(convertTime(millis));
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 40);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button_start).setOnClickListener(this);
findViewById(R.id.button_calibrate).setOnClickListener(this);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
String threshold = getPreferences(MODE_PRIVATE).getString("sensitivity", "15");
calibrateThreshold = Integer.valueOf(threshold);
timerLabel = (TextView) findViewById(R.id.text_timer);
statusLabel = (TextView) findViewById(R.id.text_status);
lap1Label = (TextView) findViewById(R.id.text_lap_1);
lap2Label = (TextView) findViewById(R.id.text_lap_2);
lap3Label = (TextView) findViewById(R.id.text_lap_3);
lapBestLabel = (TextView) findViewById(R.id.text_lap_best);
startButton = (Button) findViewById(R.id.button_start);
statusLabel.setText(getString(R.string.label_status_init));
startButton.setEnabled(false);
}
#Override
public void onStart() {
super.onStart();
// show help
if (getPreferences(MODE_PRIVATE).getString("first_time", "1").equals("1")) {
showAlertBox();
getPreferences(MODE_PRIVATE).edit().putString("first_time", "0").commit();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
synchronized (this) {
try {
mCamera = Camera.open();
}
catch (RuntimeException e) {
// camera service already in use: schianta
new AlertDialog.Builder(this).setMessage(getString(R.string.error_camera_locked_text)).setTitle("Error").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TimerActivity.this.finish();
}
}).show();
return;
}
if (mCamera == null) {
// camera not found: schianta
new AlertDialog.Builder(this).setMessage(getString(R.string.error_camera_null_text)).setTitle("Error").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TimerActivity.this.finish();
}
}).show();
return;
}
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size mCameraSize = parameters.getPreviewSize();
int bytesPerPixel = ImageFormat.getBitsPerPixel(parameters.getPreviewFormat());
int bufferSize = (mCameraSize.width * mCameraSize.height * bytesPerPixel) >> 3;
mCamera.addCallbackBuffer(new byte[bufferSize]);
mCamera.addCallbackBuffer(new byte[bufferSize]);
mCamera.addCallbackBuffer(new byte[bufferSize]);
pixelOffset[0] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.1));
pixelOffset[1] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.5));
pixelOffset[2] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.9));
mCamera.setDisplayOrientation(90);
try {
mCamera.setPreviewDisplay(arg0);
}
catch (IOException e) {
Log.e("Camera", "Could not set preview display");
}
mCamera.setPreviewCallbackWithBuffer(this);
mCamera.startPreview();
isPreviewRunning = true;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
synchronized (this) {
try {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
isPreviewRunning = false;
}
}
catch (Exception e) {
Log.e("Camera", e.getMessage());
}
finally {
if (mCamera != null) {
mCamera.release();
}
}
}
}
#Override
public void onPreviewFrame(byte[] yuv, Camera arg1) {
int value0 = (int) yuv[pixelOffset[0]] & 0xFF;
int value1 = (int) yuv[pixelOffset[1]] & 0xFF;
int value2 = (int) yuv[pixelOffset[2]] & 0xFF;
// sto calibrando...
if (isCalibrating) {
frame++;
Log.d("Timer", "Calibrating, " + value0 + ";" + value1 + ";" + value2);
calibrateRange[0][frame - 1] = value0;
calibrateRange[1][frame - 1] = value1;
calibrateRange[2][frame - 1] = value2;
if (frame >= 20) {
// finito di calibrare
isCalibrating = false;
isCalibrated = true;
startButton.setEnabled(true);
statusLabel.setText(getString(R.string.label_status_ready));
// calcolo la media
int tot0 = 0, tot1 = 0, tot2 = 0;
for (int i = 0; i < 20; i++) {
tot0 += calibrateRange[0][i];
tot1 += calibrateRange[1][i];
tot2 += calibrateRange[2][i];
}
calibrateValue[0] = tot0 / 20;
calibrateValue[1] = tot1 / 20;
calibrateValue[2] = tot2 / 20;
Log.d("Timer", "Calibrated on [" + calibrateValue[0] + "][" + calibrateValue[1] + "][" + calibrateValue[2] + "]");
}
}
// sono in ascolto di variazioni
else if (isStarted) {
// catch del frame
if (isCalibrated && (value0 < calibrateValue[0] - calibrateThreshold || value0 > calibrateValue[0] + calibrateThreshold || value1 < calibrateValue[1] - calibrateThreshold || value1 > calibrateValue[1] + calibrateThreshold || value2 < calibrateValue[2] - calibrateThreshold || value2 > calibrateValue[2] + calibrateThreshold)) {
// se ho catchato il frame precedente, ignoro
if (!caughtPreviousFrame) {
Log.d("Timer", "Frame caught!");
caughtPreviousFrame = true;
if (isTimerRunning) {
// calcolo dei lap
long catchTime = SystemClock.uptimeMillis();
lapCount++;
long lapTime = catchTime - mLastCatchTime;
laps.add(lapTime);
if (lapCount == 1) {
bestLap = lapTime;
}
else if (bestLap > lapTime) {
bestLap = lapTime;
}
printLaps();
mLastCatchTime = catchTime;
}
else {
// devo far partire il timer
isTimerRunning = true;
mStartTime = SystemClock.uptimeMillis();
mLastCatchTime = mStartTime;
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 50);
}
}
}
else {
caughtPreviousFrame = false;
}
}
mCamera.addCallbackBuffer(yuv);
fps.logFrame();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_start: {
if (!isCalibrated || isCalibrating) {
// non è calibrato
break;
}
if (isStarted) {
// ho stoppato
startButton.setText("Start");
statusLabel.setText(getString(R.string.label_status_ready));
isStarted = false;
isTimerRunning = false;
mHandler.removeCallbacks(mUpdateTimeTask);
}
else {
// ho startato
startButton.setText("Stop");
statusLabel.setText(getString(R.string.label_status_started));
timerLabel.setText("0:00:0");
isStarted = true;
mStartTime = 0L;
lapCount = 0;
// resetto i laps
laps = new ArrayList<Long>();
bestLap = 0;
printLaps();
}
break;
}
case R.id.button_calibrate: {
if (isTimerRunning) {
// devo stoppare prima di calibrare
break;
}
// ho pigiato calibra, devo resettare tutto
statusLabel.setText(getString(R.string.label_status_calibrating));
timerLabel.setText("0:00:0");
frame = 0;
mStartTime = 0L;
lapCount = 0;
isStarted = false;
isTimerRunning = false;
isCalibrating = true;
isCalibrated = false;
// resetto i laps
laps = new ArrayList<Long>();
bestLap = 0;
printLaps();
break;
}
}
}
private String convertTime(long millis) {
if (millis == 0) {
return "0:00:0";
}
timerBuffer = new StringBuffer();
int split = ((int) (millis / 100)) % 10;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
timerBuffer.append(minutes).append(":0").append(seconds).append(":").append(split);
return timerBuffer.toString();
}
else {
timerBuffer.append(minutes).append(":").append(seconds).append(":").append(split);
return timerBuffer.toString();
}
}
private void printLaps() {
lapBuffer = new StringBuffer();
try {
lapBuffer.append("Lap ").append(lapCount).append(": ").append(convertTime(laps.get(laps.size() - 1)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append("Lap ").append(lapCount).append(": ").append(convertTime(0));
}
lap1Label.setText(lapBuffer.toString());
lapBuffer = new StringBuffer();
if (lapCount > 1) {
lapBuffer.append("Lap ").append(lapCount - 1);
}
else {
lapBuffer.append("Lap 0");
}
try {
lapBuffer.append(": ").append(convertTime(laps.get(laps.size() - 2)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append(": ").append(convertTime(0));
}
lap2Label.setText(lapBuffer.toString());
lapBuffer = new StringBuffer();
if (lapCount > 2) {
lapBuffer.append("Lap ").append(lapCount - 2);
}
else {
lapBuffer.append("Lap 0");
}
try {
lapBuffer.append(": ").append(convertTime(laps.get(laps.size() - 3)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append(": ").append(convertTime(0));
}
lap3Label.setText(lapBuffer.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_tutorial: {
showAlertBox();
return true;
}
case R.id.menu_sensitivity: {
// devo stoppare tutto
startButton.setText("Start");
statusLabel.setText(getString(R.string.label_status_ready));
isStarted = false;
isTimerRunning = false;
mHandler.removeCallbacks(mUpdateTimeTask);
Intent i = new Intent(this, SensitivityDialogActivity.class);
startActivity(i);
return true;
}
case R.id.menu_email: {
if (isStarted || isTimerRunning) {
Toast.makeText(this, getString(R.string.error_timer_started), Toast.LENGTH_SHORT).show();
return true;
}
if (laps == null || laps.size() == 0) {
Toast.makeText(this, getString(R.string.error_laps_empty), Toast.LENGTH_SHORT).show();
return true;
}
String emailBody = lapsToString();
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailBody);
startActivity(Intent.createChooser(emailIntent, getString(R.string.menu_mail_laps)));
return true;
}
}
return false;
}
public void showAlertBox() {
new AlertDialog.Builder(this).setMessage(getString(R.string.dialog_tutorial_text)).setTitle("Tutorial").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
private String lapsToString() {
StringBuffer s = new StringBuffer();
s.append("Mini 4WD Android Lap Timer data");
s.append("\n\n");
for (int i = 0; i < laps.size(); i++) {
long lap = laps.get(i);
s.append("Lap ").append(i + 1).append(": ").append(convertTime(lap)).append("\n");
}
s.append("\n");
s.append("Best lap: " + convertTime(bestLap));
return s.toString();
}
}
thank you in advance.. :)
I am developing an application to receive data on an Android device from an Arduino. It displays values only up to 255 when I convert it to integer, but I want those values which are sent by the Arduino board. I have tried converting them to strings but that didn't work either.
How can I solve this problem?
Here's the code running on the Android device:
package pkg.MultipleDataReceiveFromArduinoArray;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import pkg.MultipleDataReceiveFromArduino.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
public class MultipleDataReceiveFromArduinoActivity extends
Activity implements Runnable {
private TextView txtReceivedBytes;
private TextView txtWaterLitres;
private TextView txtSensor1;
private TextView txtSensor2;
private TextView txtSensor3;
private EditText etCallibrationValue;
private Button btnSetCallibrationValue;
private static final String ACTION_USB_PERMISSION =
"com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
int countWaterVol = 0;
private int intCallibrationValue = 270;
private static final int MESSAGE_TEMPERATURE = 1;
private static final int MESSAGE_HUMIDITY = 2;
private static final int MESSAGE_WATERLEVEL = 3;
private static final byte COMMAND_OPEN_DOOR = 0x01;
private static final byte COMMAND_CLOSE_DOOR = 0x02;
protected class TelemetryPacket {
private int value;
public TelemetryPacket(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private int composeInt(byte hi, byte lo) {
int val = (int) hi & 0xff;
val *= 256;
val += (int) lo & 0xff;
return val;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtReceivedBytes=(TextView)findViewById(R.id.txtReceivedBytes);
txtWaterLitres =(TextView)findViewById(R.id.txtWaterLitres);
txtSensor1 = (TextView) findViewById(R.id.txtSensor1);
txtSensor2 =(TextView)findViewById(R.id.txtSensor2);
txtSensor3 =(TextView)findViewById(R.id.txtSensor3);
etCallibrationValue = (EditText)findViewById(R.id.etCallibrationValue);
btnSetCallibrationValue =
(Button)findViewById(R.id.btnSetCallibrationValue);
setupAccessory();
btnSetCallibrationValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intCallibrationValue =
Integer.parseInt(etCallibrationValue.getText().toString());
Toast.makeText(getApplicationContext(),
"Callibration Value:" + intCallibrationValue,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
if (mInputStream != null && mOutputStream != null) {
// streams were not null");
return;
}
// streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(
accessory, mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
// null accessory
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//TelemetryPacket p = (TelemetryPacket) msg.obj;
ValueMsg t = (ValueMsg) msg.obj;
txtReceivedBytes.setText("Received Bytes: "+t.getRet());
if (t.getReading4()==1) {
countWaterVol = countWaterVol+1;
txtWaterLitres.setText("Water Produced in Litres:"+
(countWaterVol+"\n"+"Interrupt Signal"+t.getReading3());
} else {
}
txtSensor1.setText("S 1: "+t.getReading1()+","+
"Reading 2: "+t.getReading2());
txtSensor2.setText("S 3: "+t.getReading3()+","+
"Reading 4: "+t.getReading4());
txtSensor3.setText("S 5: "+t.getReading5()+","+
"Reading 6: "+t.getReading6());
Alets alerts = new Alets();
}
};
private void setupAccessory() {
mUsbManager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
// Accessory opened
} else {
// failed to open accessory
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void run() {
int ret = 0;
//byte[] buffer = new byte[16384];
byte[] buffer = new byte[65536];
int i;
while (true) { // read data
try {
ret = mInputStream.read(buffer);
//ret= ret/3;
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
// if (len >= 1) {
int value = (int) buffer[0];
Message m = Message.obtain(mHandler);
m.obj = new ValueMsg('f',value,ret,buffer[1],buffer[2],
buffer[3],buffer[4],buffer[5]);
mHandler.sendMessage(m);
i += 1;
}
}
}
public static final long unsignedIntToLong(byte[] b)
{
long l = 0;
l |= b[0] & 0xFF;
l <<= 8;
l |= b[1] & 0xFF;
l <<= 8;
l |= b[2] & 0xFF;
l <<= 8;
l |= b[3] & 0xFF;
return l;
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0x10;
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
// USB permission denied
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (accessory != null && accessory.equals(mAccessory)) {
// accessory detached
closeAccessory();
}
}
}
};
}
And here's the Arduino code (sketch):
#include <Usb.h>
#include <adk.h>
uint8_t b;
USB Usb;
ADK adk(&Usb,
"Ashok Kateshiya", // Manufacturer Name
"analog TEST", // Model Name
"TDS test ", // Description (user-visible string)
"0.1", // Version
"http://www.ashokkateshiya.co.cc",
"123456789"); // Serial Number (optional)
#define tds_pin A15
#define flow_pin 22
#define LLS_pin 49
float avg[10];
float value = 0;
int count;
int pin_state = 0, pin_old_state = 0;
int pulse_counter = 0;
int LLS_state;
int LLS_flag = 0;
int sensor_flag = 0;
int timer_flag = 0;
uint8_t msg[7] = { 0x00 };
uint16_t len = sizeof(msg);
uint8_t rcode;
void setup()
{
Serial.begin(115200);
Serial.print("\r\nADK demo start");
if (Usb.Init() == -1)
{
Serial.print("\r\nOSCOKIRQ failed to assert");
while(1); // halt
}
pinMode(tds_pin, INPUT);
pinMode(flow_pin, INPUT);
pinMode(LLS_pin, INPUT);
digitalWrite(LLS_pin, HIGH);
digitalWrite(flow_pin, HIGH);
TIMSK1 = 0x01;
TCCR1A = 0x00;
TCNT1 = 0x85EF;
TCCR1B = 0x05;
}
void loop()
{
Usb.Task();
if (adk.isReady() == false)
{
return;
}
TDS();
flow();
LLS();
}
void TDS()
{
for (count = 0; count < 10; count++)
{
avg[count] = analogRead(tds_pin);
}
for (count = 0; count < 10; count ++)
{
if (count == 0)
{
value = avg[count];
}
else
{
value = value + avg[count];
}
}
if (len > 0)
{
msg[0] = 0x1;
msg[1] = value/10;
rcode = adk.SndData (6, msg );
Serial.print("TDS 0 : ");
Serial.println(msg[0]);
Serial.print("TDS 1 : ");
Serial.println(msg[1]);
delay(10);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
}
void flow()
{
pin_state = digitalRead(flow_pin);
if (pin_state == LOW)
{
pin_old_state = pin_state;
}
if ((pin_state == HIGH) && (pin_old_state == LOW))
{
pin_old_state = pin_state;
pulse_counter = (pulse_counter + 1);
sensor_flag = 1;
}
if ((pulse_counter / 25 == 1) && (sensor_flag == 1))
{
pulse_counter = 0;
sensor_flag = 0;
msg[2] = 0x2;
msg[3] = 1;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
else
{
msg[2] = 0x2;
msg[3] = 0;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
delay(10);
}
void LLS()
{
LLS_state = digitalRead(LLS_pin);
if (LLS_state != 0)
{
if (len > 0)
{
msg[4] = 0x3;
msg[5] = 0x0;
rcode = adk.SndData (6, msg );
Serial.print("LLS 4 : ");
Serial.println(msg[4]);
Serial.print("LLS 5 : ");
Serial.println(msg[5]);
}
}
else
{
msg[4] = 0x3;
msg[5] = 0x1;
rcode = adk.SndData (6, msg );
Serial.print("LLS 0 : ");
Serial.println(msg[4]);
Serial.print("LLS 2 : ");
Serial.println(msg[5]);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
delay(10);
}
/****** timer overflow *******/
ISR(TIMER1_OVF_vect)
{
TCNT1 = 0x85EF;
if (pin_state == pin_old_state )
{
timer_flag = 1;
}
}
It looks like the problem is in the Arduino sketch. The msg array contains (unsigned) bytes which have a maximum value of 255.
The line:
msg[1] = value/10
implicitly truncates value/10 (which is an integer between 0 and 1023 - see http://arduino.cc/en/Reference/analogRead) to a maximum of 255.
To send value/10 you'll need to split it over 2 bytes. For example:
msg[1] = (uint8_t) (i & 0xFF);
msg[2] = (uint8_t) ((i >> 8) & 0xFF);
And msg will have to be one byte longer to accomodate.
On the Android (Java) side you'll need to do something like:
int value = (int) buffer[0];
// ...
int tds = buffer[1] + (buffer[2] << 8);
m.obj = new ValueMsg('f', value, ret, tds,
buffer[3], buffer[4], buffer[5], buffer[6]);
which will require a change to the definition of ValueMsg to accomodate.
Also, there may be a problem with the calls to SndData (assuming the library being used here is the USB_Host_Shield_2.0) as they always send 6 bytes even though in the first time through loop all 6 bytes of msg won't have been initialized.