Android App Communicating with USB CDC Device - android

I am Developing Android App That Receive Data From USB CDC Device.
Thinking that my android phone is host. The Device should get power from the android phone only. The cable Used for Data Transfer and power is Same.
But here Data Not Receiving from USB CDC Device to Mobile.
Here is code snippet from what I have tried
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Iterator;
public class MainActivity extends Activity {
boolean Run= true;
boolean Communication_Ok;
Button btn;
UsbManager manager;
UsbDevice device;
UsbDeviceConnection connection;
UsbInterface Inf;
UsbEndpoint Data_In_End_Point =null;
UsbEndpoint Data_Out_End_Point =null;
ByteBuffer buffer = ByteBuffer.allocate(255);
UsbRequest request = new UsbRequest();
static int s1,s2,s3;
TextView tv1;
PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.btn);
tv1=(TextView)findViewById(R.id.tv1);
check_devices();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
call_next_Intent();
if (!Receive.isAlive())
Receive.start();
}
});
}
private void call_next_Intent() {
Intent Home=new Intent(MainActivity.this,Home.class);
startActivity(Home);
}
private void check_devices()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
HashMap<String , UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String returnValue = "";
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
returnValue += "Name: " + device.getDeviceName();
returnValue += "\nID: " + device.getDeviceId();
returnValue += "\nProtocol: " + device.getDeviceProtocol();
returnValue += "\nClass: " + device.getDeviceClass();
returnValue += "\nSubclass: " + device.getDeviceSubclass();
returnValue += "\nProduct ID: " + device.getProductId();
returnValue += "\nVendor ID: " + device.getVendorId();
returnValue += "\nInterface count: " + device.getInterfaceCount();
for (int i = 0; i < device.getInterfaceCount(); i++) {
Inf = device.getInterface(i);
returnValue += "\n Interface " + i;
returnValue += "\n\tInterface ID: " + Inf.getId();
returnValue += "\n\tClass: " + Inf.getInterfaceClass();
returnValue += "\n\tProtocol: " + Inf.getInterfaceProtocol();
returnValue += "\n\tSubclass: " + Inf.getInterfaceSubclass();
returnValue += "\n\tEndpoint count: " + Inf.getEndpointCount();
for (int j = 0; j < Inf.getEndpointCount(); j++) {
returnValue += "\n\t Endpoint " + j;
returnValue += "\n\t\tAddress: " + Inf.getEndpoint(j).getAddress();
returnValue += "\n\t\tAttributes: " + Inf.getEndpoint(j).getAttributes();
returnValue += "\n\t\tDirection: " + Inf.getEndpoint(j).getDirection();
returnValue += "\n\t\tNumber: " + Inf.getEndpoint(j).getEndpointNumber();
returnValue += "\n\t\tInterval: " + Inf.getEndpoint(j).getInterval();
returnValue += "\n\t\tType: " + Inf.getEndpoint(j).getType();
returnValue += "\n\t\tMax packet size: " + Inf.getEndpoint(j).getMaxPacketSize();
}
}
}
tv1.setText(returnValue);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if(device != null)
{
connection = manager.openDevice(device);
if (!connection.claimInterface(device.getInterface(0), true))
{
return;
}
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
connection.controlTransfer(0x21, 0x22, 0x1, 0, null, 0, 0);//DTR signal
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
connection.controlTransfer(0x40, 0x03,0x001A, 0, null, 0, 0);//For baudrate
Inf = device.getInterface(0);
for (int i = 0; i < device.getInterfaceCount(); i++) {
// communications device class (CDC) type device
if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
Inf = device.getInterface(i);
// find the endpoints
for (int j = 0; j < Inf.getEndpointCount(); j++) {
if (Inf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT && Inf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
// from android to device
Data_Out_End_Point = Inf.getEndpoint(j);
}
if (Inf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN && Inf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
// from device to android
Data_In_End_Point = Inf.getEndpoint(j);
}
}
}
}
}
}
else
{
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
public Thread Receive = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] Recieved_Data;
int i;
buffer.clear();
while (Run){
request.initialize(connection, Data_In_End_Point);
request.queue(buffer,255);
if (connection.requestWait() !=null)
{
Recieved_Data=buffer.array();
if (Recieved_Data[0]==0x02 && Recieved_Data[2]==0x03){
if (Recieved_Data[1]==0x11){
s1++;
}
else if (Recieved_Data[1]==0x22){
s2++;
}
else if (Recieved_Data[1]==0x33){
s3++;
}
}
}
}
}
});
}

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

Selendroid webdriver initialisation error occuring

I am making an android application which will login to my college website then clicks on attendance button on the page , scraps data ,perform some calculations and shows to the user but I can't find any way from here. I am using selendroid for this. The problem is with the driver variable. In java application I can use ChromeDriver but for android what to use?
package com.example.jtx.gneattendance;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.List;
import io.selendroid.SelendroidCapabilities;
import io.selendroid.SelendroidDriver;
import io.selendroid.standalone.SelendroidLauncher;
public class MainActivity extends AppCompatActivity {
int count = 0;
String arr[] = new String[15];
String atten = "";
TextView text;
public void cnt() throws Exception
{
WebDriver driver =null;
driver.get("https://academics.gndec.ac.in");
driver.findElement(By.id("username")).sendKeys("xxxxxxxxx");
driver.findElement(By.id("password")).sendKeys("xxxxxxxxx");
driver.findElement(By.name("submit")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div/div[2]/form/button")).click();
List<WebElement> rows = driver.findElements(By.xpath("/html/body/form/table/tbody/tr"));
String p[] = new String[rows.size() + 1];
int pheld[] = new int[rows.size() + 1];
int pattende[] = new int[rows.size() + 1];
Double ppercent[] = new Double[rows.size() + 1];
for (int i = 1; i <= rows.size(); i++) {
p[i] = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[2]")).getText();
pheld[i] = Integer.parseInt(driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[4]")).getText());
pattende[i] = Integer.parseInt(driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[5]")).getText());
ppercent[i] = Double.valueOf((driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[6]")).getText()));
if (ppercent[i] < 75.0) {
lecreq(pattende[i], pheld[i]);
}
arr[i] = " Subject name=" + p[i] + "<br> Lectures held=" + pheld[i] + " <br> Lectures Attended=" + pattende[i] + " <br> Percentage=" + ppercent[i] + " <br> Lectures needed=" + count + "<br><br><br>";
// System.out.println(arr[i]);
text = findViewById(R.id.textView1);
text.setText(arr[i]);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
cnt();
} catch (Exception e) {
e.printStackTrace();
}
}
public void lecreq(int m, int n) {
if ((m * 100 / n) < 75.0) {
m++;
n++;
count++;
lecreq(m, n);
}
}
}

Can Adafruit FT232H Breakout be used for Android smartphones?

As the title describes, can Adafruit FT232H Breakout be used as a GPIO interface between peripherals such as sensors and Android smartphones?
Yes. It requires the d2xx.jar from FTDI in your libs/ directory. Then you can use the example provided by FTDI to attach to the device.
Here is my MainActivity.java that I have to attach to an FT232H from Adafruit:
package com.XXXXX.ftdi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
public class MainActivity extends AppCompatActivity {
public static D2xxManager ftD2xx = null;
FT_Device ftDevice = null;
static Context DeviceInformationContext;
int devCount=0;
TextView textNumberDeviceValue;
TextView textDeviceName;
TextView textDeviceSerialNo;
TextView textDeviceDescription;
TextView textDeviceID;
TextView textDeviceLocation;
TextView textLibrary;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetupD2xxLibrary();
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.setPriority(500);
textNumberDeviceValue = findViewById(R.id.numDev);
textDeviceName = findViewById(R.id.devName);
textDeviceSerialNo = findViewById(R.id.device_information_serialno);
textDeviceDescription = findViewById(R.id.device_information_description);
textDeviceID = findViewById(R.id.device_information_deviceid);
textDeviceLocation = findViewById(R.id.device_information_devicelocation);
textLibrary = findViewById(R.id.device_information_library);
devCount = -1;
ConnectFunction();
try {
GetDeviceInformation();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
String s = e.getMessage();
e.printStackTrace();
}
this.registerReceiver(mUsbReceiver, filter);
}
private void SetupD2xxLibrary () {
/*
PackageManager pm = getPackageManager();
for (ApplicationInfo app : pm.getInstalledApplications(0)) {
Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.nativeLibraryDir);
if (app.packageName.equals(R.string.app_name)) {
System.load(app.nativeLibraryDir + "/libj2xx-utils.so");
Log.i("ftd2xx-java","Get PATH of FTDI JIN Library");
break;
}
}
*/
// Specify a non-default VID and PID combination to match if required
//if(!ftD2xx.setVIDPID(0x0403, 0xada1))
if(!ftD2xx.setVIDPID(0x0403, 0x6014))
Log.i("ftd2xx-java","setVIDPID Error");
}
/***********USB broadcast receiver*******************************************/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String TAG = "FragL";
String action = intent.getAction();
if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
{
Log.i(TAG,"DETACHED...");
}
}
};
public void GetDeviceInformation() throws InterruptedException {
//int devCount = 0;
// devCount = ftD2xx.createDeviceInfoList(DeviceInformationContext);
Log.i("FtdiModeControl",
"Device number = " + Integer.toString(devCount));
if (devCount > 0) {
D2xxManager.FtDeviceInfoListNode[] deviceList = new D2xxManager.FtDeviceInfoListNode[devCount];
ftD2xx.getDeviceInfoList(devCount, deviceList);
deviceList[0] = ftD2xx.getDeviceInfoListDetail(0);
textNumberDeviceValue.setText("Number of Devices: "
+ Integer.toString(devCount));
if (deviceList[0].serialNumber == null) {
textDeviceSerialNo.setText("Device Serial Number: " + deviceList[0].serialNumber + "(No Serial Number)");
} else {
textDeviceSerialNo.setText("Device Serial Number: " + deviceList[0].serialNumber);
}
if (deviceList[0].description == null) {
textDeviceDescription.setText("Device Description: " + deviceList[0].description+ "(No Description)");
} else {
textDeviceDescription.setText("Device Description: " + deviceList[0].description);
}
textDeviceLocation.setText("Device Location: " + String.format("%04x",deviceList[0].location));
textDeviceID.setText("Device ID: " + String.format("%08x",deviceList[0].id));
int libVersion = D2xxManager.getLibraryVersion();
textLibrary.setText("Library Version: " + convertIntToBcdString(libVersion) );
// display the chip type for the first device
switch (deviceList[0].type) {
case D2xxManager.FT_DEVICE_232B:
textDeviceName.setText("Device Name : FT232B device");
break;
case D2xxManager.FT_DEVICE_8U232AM:
textDeviceName.setText("Device Name : FT8U232AM device");
break;
case D2xxManager.FT_DEVICE_UNKNOWN:
textDeviceName.setText("Device Name : Unknown device");
break;
case D2xxManager.FT_DEVICE_2232:
textDeviceName.setText("Device Name : FT2232 device");
break;
case D2xxManager.FT_DEVICE_232R:
textDeviceName.setText("Device Name : FT232R device");
break;
case D2xxManager.FT_DEVICE_2232H:
textDeviceName.setText("Device Name : FT2232H device");
break;
case D2xxManager.FT_DEVICE_4232H:
textDeviceName.setText("Device Name : FT4232H device");
break;
case D2xxManager.FT_DEVICE_232H:
textDeviceName.setText("Device Name : FT232H device");
break;
case D2xxManager.FT_DEVICE_X_SERIES:
textDeviceName.setText("Device Name : FTDI X_SERIES");
break;
case D2xxManager.FT_DEVICE_4222_0:
case D2xxManager.FT_DEVICE_4222_1_2:
case D2xxManager.FT_DEVICE_4222_3:
textDeviceName.setText("Device Name : FT4222 device");
break;
default:
textDeviceName.setText("Device Name : FT232B device");
break;
}
} else {
textNumberDeviceValue.setText("Number of devices: 0");
textDeviceName.setText("Device Name : No device");
textDeviceSerialNo.setText("Device Serial Number: NULL");
textDeviceDescription.setText("Device Description: None");
textDeviceLocation.setText("Device Location: Nowhere");
textDeviceID.setText("Device ID: None");
textLibrary.setText("Library Version: None");
}
}
String convertIntToBcdString(int num)
{
String str = "";
str = Integer.toString((num>>28) & 0xf) + "." +
Integer.toString((num>>24) & 0xf) +
Integer.toString((num>>20) & 0xf) + "." +
Integer.toString((num>>16) & 0xf) +
Integer.toString((num>>12) & 0xf) + "." +
Integer.toString((num>>8) & 0xf) +
Integer.toString((num>>4) & 0xf) +
Integer.toString(num & 0xf);
return str;
}
public void ConnectFunction() {
int openIndex = 0;
if (devCount > 0)
return;
devCount = ftD2xx.createDeviceInfoList(this);
if (devCount > 0) {
ftDevice = ftD2xx.openByIndex(this, openIndex);
if(ftDevice == null)
{
Toast.makeText(this,"ftDev == null",Toast.LENGTH_LONG).show();
return;
}
if (true == ftDevice.isOpen())
{
ftDevice.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDevice.setBaudRate(9600);
ftDevice.setDataCharacteristics(D2xxManager.FT_DATA_BITS_8,
D2xxManager.FT_STOP_BITS_1, D2xxManager.FT_PARITY_NONE);
ftDevice.setFlowControl(D2xxManager.FT_FLOW_NONE, (byte) 0x00, (byte) 0x00);
ftDevice.setLatencyTimer((byte) 16);
ftDevice.purge((byte) (D2xxManager.FT_PURGE_TX | D2xxManager.FT_PURGE_RX));
}
else
{
Toast.makeText(this, "Need to get permission!",Toast.LENGTH_SHORT).show();
}
}
else
{
Log.e("j2xx", "DevCount <= 0");
}
}
}

My Android application is crashing if it is not connected to wifi

package com.example.intracollegeapp;// package name
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import LibPack.UserInfoLib;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class LoginForm extends Activity {
Button login;
TextView username;
TextView password;
UserInfoLib ui;
long msgLength;
long bitLength;
char msg[];
long requiredBits;
long requiredBytes;
int toPad[];
private static final String NAMESPACE = "link to server package on which webservices are stored";
private static final String URL = "link to wsdl file stored on server";
private static final String SOAP_ACTION = "IntraCollegeWS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
login=(Button)findViewById(R.id.butLogin);
username=(TextView)findViewById(R.id.editText1);
password=(TextView)findViewById(R.id.editText2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ui= new UserInfoLib();
ui.userId=username.getText().toString();
ui.password=getSHA1(password.getText().toString());
ui=(UserInfoLib)callService(objectToString(ui), "UserLogin", "userInfo");
//ui=(UserInfoLib)stringToObject(temp);
if(ui.firstName.equals("")){
Toast.makeText(v.getContext(), "Please Verify User Name Or Password", Toast.LENGTH_LONG).show();
finish();
}else{
Toast.makeText(v.getContext(), "Login Successfull", Toast.LENGTH_LONG).show();
System.out.println("NAME :"+ui.firstName);
Intent i = new Intent(v.getContext(), MainForm.class);
i.putExtra("uid", ui);
startActivity(i);
finish();
}
}
});
}
public long leftRotateBy(long l, int times) {
return ((l << times) & 0xFFFFFFFFl) | ((l & 0xFFFFFFFFl) >> (32 - times));
}
public int getByteAt(int at) {
if (at < msgLength) {
return (msg[at]);
} else {
at = at - (int) msgLength;
return toPad[at];
}
}
public void padBits(String pass) {
System.out.println("\n\n\n\n");
msg = pass.toCharArray();
msgLength = msg.length;
bitLength = msgLength * 8;
System.out.println("Msg Bit Length: " + bitLength);
System.out.println("MSg Byte Length: " + msgLength);
System.out.println("Required Minimum Bits: " + (bitLength + 65));
long remainder = (bitLength + 65) % 512;
System.out.println("Mod (Bits): " + remainder);
if (remainder == 0) {
requiredBits = 65;
System.out.println("No Padding Needed.");
} else {
requiredBits = (512 - remainder) + 65;
System.out.println(requiredBits + " Bits Padding Needed.");
}
requiredBytes = requiredBits / 8;
toPad = new int[(int) requiredBytes];
System.out.println("Required Bits: " + requiredBits);
System.out.println("Required Bytes: " + requiredBytes);
// manually append 1 to start of pad bits...
toPad[0] = 0x80;
for (int i = 1; i < requiredBytes - 8; i++) {
toPad[i] = 0;
}
long temp = bitLength;
for (int i = (int) (requiredBytes - 1); i >= (int) (requiredBytes - 8); i--) {
int t = (int) (temp & 0xff);
temp = temp >> 8;
toPad[i] = t;
}
System.out.println("TO PAD: ");
for (int i = 0; i < requiredBytes; i++) {
System.out.print(Integer.toHexString(toPad[i]) + " ");
}
System.out.println();
}
public String getSHA1(String pass) {
int kconst[] = new int[]{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6};
long h0 = 0x67452301;
long h1 = 0xEFCDAB89;
long h2 = 0x98BADCFE;
long h3 = 0x10325476;
long h4 = 0xC3D2E1F0;
long a, b, c, d, e;
padBits(pass);
long totalLength = msgLength + requiredBytes;
System.out.println("TOTAL LENGTH: " + totalLength);
System.out.println("BLOCKS: " + (totalLength / 8));
long w[] = new long[80];
for (int i = 0; i < (int) totalLength; i += 64) {
for (int j = i, kk = 0; j < (i + 64); j += 4, kk++) {
w[kk] = 0xffffffffl & ((getByteAt(j) << 24) | (getByteAt(j + 1) << 16) | (getByteAt(j + 2) << 8) | (getByteAt(j + 3)));
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
for (int kk = 16; kk < 80; kk++) {
w[kk] = (w[kk - 3] ^ w[kk - 8] ^ w[kk - 14] ^ w[kk - 16]);
w[kk] = leftRotateBy(w[kk], 1);
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
long temp = 0;
for (int t = 0; t < 20; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | ((~b) & d)) + e + w[t] + kconst[0];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 20; t < 40; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[1];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 40; t < 60; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | (b & d) | (c & d)) + e + w[t] + kconst[2];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 60; t < 80; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[3];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFFl;
h1 = (h1 + b) & 0xFFFFFFFFl;
h2 = (h2 + c) & 0xFFFFFFFFl;
h3 = (h3 + d) & 0xFFFFFFFFl;
h4 = (h4 + e) & 0xFFFFFFFFl;
}
return Long.toHexString(h0) + Long.toHexString(h1) + Long.toHexString(h2) + Long.toHexString(h3) + Long.toHexString(h4);
}
Object callService(String INPUT_DATA, String METHOD_NAME, String PARAMETER_NAME){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo pi = new PropertyInfo();
pi.setName(PARAMETER_NAME);
pi.setValue(INPUT_DATA);
pi.setType(String.class);
request.addProperty(pi);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject)envelope.bodyIn;
String resp = resultsRequestSOAP.getPrimitivePropertyAsString("return");
return stringToObject(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Object stringToObject(String inp){
byte b[] = Base64.decode(inp);
Object ret = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
ret = (Object) in.readObject();
bis.close();
in.close();
} catch(Exception e) {
System.out.println("NOT DE-SERIALIZABLE: " + e);
}
return ret;
}
String objectToString(Object obj){
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
b = bos.toByteArray();
} catch(Exception e) {
System.out.println("NOT SERIALIZABLE: " + e);
}
return Base64.encode(b);
}
}
/* i have developed an android application which connects to server for login purpose. For connection i have used ksoap2 library. Intracollege webservice is stored on server. The application works fine when connected to server using wifi. if it is not connected to wifi it displays message "application is crashed" and then application stops working.
I only want to display a simple message "Application is not connected to server" if it is not connected to server using wifi.*/
Try this........
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
When status is true do your login process.Otherwise show message "Application is not connected to server".
To check for the internet connection try this out
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Check this code, this will help you :
Initialize in the class where you want to check network availability.
OtherUtils otherUtils = new OtherUtils();
if (!otherUtils.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "No Network Available", Toast.LENGTH_LONG).show();
return;
}
Add below class:
public class OtherUtils{
Context context;
public boolean isNetworkAvailable(Context context) {
this.context = context;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
// boitealerte(this.getString(R.string.alertNoNetwork),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
This will surely help you.

Android get Tcp connection log

I have some trouble in getting Tcp connection log of all apps. Basically, I just read the log file "/proc/Pid/net/tcp" as used here:
http://code.google.com/p/iptableslog/source/browse/src/com/googlecode/networklog/NetStat.java?r=60cb640ac27f8b4fb06f11d9d81c94591a531862
But all the destination ip address are 0.0.0.0, though some apps are connecting to Internet.
Here is my source code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textmpid = (TextView) findViewById(R.id.textView2);
Button buttonLoadTrafficStats = (Button) findViewById(R.id.button1);
buttonLoadTrafficStats.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ActivityManager mActivityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses();
int i = 1;
int a;
String b;
int c;
for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess){
//Get name, Pid, Uid of all running process
System.out.println("Application: " +i+ " PID: " + amProcess.pid+ " (processName= " + amProcess.processName + " UID= "+amProcess.uid+")");
Log.i("Application", (i++) + "PID: " + amProcess.pid + "(processName=" + amProcess.processName + "UID="+amProcess.uid+")");
i++;
textmpid.setText("PID: "+ String.valueOf(amProcess.pid));
a = amProcess.pid;
b = String.valueOf(amProcess.pid);
ArrayList<Connection> connections = new ArrayList<Connection>();
try {
BufferedReader in = new BufferedReader(new FileReader("/proc/" + a + "/net/tcp"));
String line = b;
int z;
while((line = in.readLine()) != null) {
System.out.println(" tcp Netstat line: " + line);
line = line.trim();
String[] fields = line.split("\\s+", 10);
int fieldn = 0;
for(String field : fields) {
System.out.println(" tcp Field " + (fieldn++) + ": [" + field + "]");
int m = fieldn;
String n = field;
}
if(fields[0].equals("sl")) {
continue;
}
Connection connection = new Connection();
String src[] = fields[1].split(":", 2);
String dst[] = fields[2].split(":", 2);
System.out.println(" tcp Netstat: fields[1] " + fields[1]+" fields[2] " + fields[2]);
System.out.println(" tcp Netstat: src[0] " + src[0] +" src[1] " + src[1]);
connection.src = getAddress(src[0]);
System.out.println(" tcp Netstat: connection.src " + connection.src);
connection.spt = String.valueOf(getInt16(src[1]));
System.out.println(" tcp Netstat: connection.spt " + connection.spt);
connection.dst = getAddress(dst[0]);
System.out.println(" tcp Netstat: connection.dst " + connection.dst);
connection.dpt = String.valueOf(getInt16(dst[1]));
System.out.println(" tcp Netstat: connection.dpt " + connection.dpt);
connection.uid = fields[7];
System.out.println(" tcp Netstat: connection.uid " + connection.uid);
connections.add(connection);
}
}
catch(Exception e) {
System.out.println(" checknetlog() Exception: " + e.toString());
}
}
}
});
}
public class Connection {
String src;
String spt;
String dst;
String dpt;
String uid;
}
final String states[] = { "ESTBLSH", "SYNSENT", "SYNRECV", "FWAIT1", "FWAIT2", "TMEWAIT",
"CLOSED", "CLSWAIT", "LASTACK", "LISTEN", "CLOSING", "UNKNOWN"
};
private final String getAddress(final String hexa) {
try {
final long v = Long.parseLong(hexa, 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final String getAddress6(final String hexa) {
try {
final String ip4[] = hexa.split("0000000000000000FFFF0000");
if(ip4.length == 2) {
final long v = Long.parseLong(ip4[1], 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} else {
return "-2.-2.-2.-2";
}
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final int getInt16(final String hexa) {
try {
return Integer.parseInt(hexa, 16);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return -1;
}
}
}
And I also added the permission "uses-permission android:name="android.permission.INTERNET".
Could someone kindly point out where I did wrong?
Oh, when I check this log "/proc/Pid/net/tcp6", I found the correct destination ip address. It seems that the connection type is tcp6 instead of tcp.

Categories

Resources