Can Adafruit FT232H Breakout be used for Android smartphones? - android

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");
}
}
}

Related

Android App Communicating with USB CDC Device

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++;
}
}
}
}
}
});
}

getCurrentInputConnection is always null

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

How can I fix (The left-hand side of an assignment must be a variable) and (Type mismatch: cannot convert from Object to String) in this code?

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.

Async with Rotation Support

EDIT: So I tried applying rotation support but every time I rotate my device the dialog pops up any ideas on what I did wrong or why it isn't keeping the dialog from displaying on a orientation change?
package com.ondrovic.bbym;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class Dashboard extends Activity {
public static final boolean usePrettyGoodSolution = false;
private ProgressDialog PROGRESS_BAR;
private Download task = null;
private static final int PROGRESS = 0;
public static File rDIR = Environment.getExternalStorageDirectory();
public static final String fDIR = "/Android/data/Bestbuy Mobile/database/";
public static final String fNAME = "bestbuy.db";
public static final String fURL = "http://db.tt/5JTRpA8q";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
task = (Download) getLastNonConfigurationInstance();
}
#Override
public Object onRetainNonConfigurationInstance() {
task.detach();
return (task);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onRestart() {
super.onRestart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
public void onClickHome(View v) {
goHome(this);
}
public void onClickUpdate(View v) {
dbDIR(fDIR);
//new Download().execute(fURL);
if (task == null) {
task = new Download(this);
task.execute(fURL);
} else {
task.attach(this);
}
}
public void onClickEmail(View v) {
// title_bar email : price quotes :-)
if (getTitle().toString().equals("Individual")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Individual Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Individual Plan"
+ "\nMinutes Package: " + Individual_ATT.packageTalk
+ "\nMessage Package: " + Individual_ATT.packageText
+ "\nData Package: " + Individual_ATT.packageData
+ "\nPrice: " + Individual_ATT.packagePrice
+ "\n\nSprint Individual Plan" + "\nPackage: "
+ Individual_SPRINT.packageInfo + "\nPrice: "
+ Individual_SPRINT.packagePrice
+ "\n\nVerizon Individual Plan" + "\nPackage: "
+ Individual_VERIZON.packageTalk + "\nData: "
+ Individual_VERIZON.packageData + "\nPrice: "
+ Individual_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Family")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Family Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Family Plan"
+ "\nMinutes Pacakge: "
+ Family_ATT.packageTalk
+ "\nMessage Package: "
+ Family_ATT.packageText
+ "\nAdditional Lines: "
+ Family_ATT.packageXtraLn
+ "\nData Package Line 1: "
+ Family_ATT.packageData1
+ "\nData Package Line 2: "
+ Family_ATT.packageData2
+ "\nData Package Line 3: "
+ Family_ATT.packageData3
+ "\nData Pacakge Line 4: "
+ Family_ATT.packageData4
+ "\nData Package Line 5: "
+ Family_ATT.packageData5
+ "\nPrice: "
+ Family_ATT.packagePrice
+ "\n\nSprint Family Plan"
+ "\nPacakge: "
+ Family_SPRINT.packageInfo
+ "\nAdditional Lines: "
+ Family_SPRINT.packageXtraLn
+ "\nLine 1 Type: "
+ Family_SPRINT.packageLine1
+ "\nLine 1 Data: "
+ Family_SPRINT.dataPriceL1
+ "\nLine 2 Type: "
+ Family_SPRINT.packageLine2
+ "\nLine 2 Data: "
+ Family_SPRINT.dataPriceL2
+ "\nLine 3 Type: "
+ Family_SPRINT.packageLine3
+ "\nLine 3 Data: "
+ Family_SPRINT.dataPriceL3
+ "\nLine 4 Type: "
+ Family_SPRINT.packageLine4
+ "\nLine 4 Data: "
+ Family_SPRINT.dataPriceL4
+ "\nLine 5 Type: "
+ Family_SPRINT.packageLine5
+ "\nLine 5 Data: "
+ Family_SPRINT.dataPriceL5
+ "\nPrice: "
+ Family_SPRINT.packagePrice
+ "\n\nVerzon Family Plan"
+ "\nPackage: "
+ Family_VERIZON.packageTalk
+ "\nAdditional Lines: "
+ Family_VERIZON.packageXtraLn
+ "\nData Pacakge Line 1: "
+ Family_VERIZON.packageData1
+ "\nData Pacakge Line 2: "
+ Family_VERIZON.packageData2
+ "\nData Pacakge Line 3: "
+ Family_VERIZON.packageData3
+ "\nData Pacakge Line 4: "
+ Family_VERIZON.packageData4
+ "\nData Pacakge Line 5: "
+ Family_VERIZON.packageData5
+ "\nPrice: "
+ Family_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Broadband")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Broadband Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Broadband Plan"
+ "\nPackage: " + Broadband_ATT.pacakgeData
+ "\nPrice: " + Broadband_ATT.packagePrice
+ "\n\nSprint Broadband Plan" + "\nPackage: "
+ Broadband_SPRINT.pacakgeData + "\nPrice: "
+ Broadband_SPRINT.packagePrice
+ "\n\nVerizon Broadband Plans" + "\nPacakge: "
+ Broadband_VERIZON.pacakgeData + "\nPrice: "
+ Broadband_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Embedded")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Embedded Plan Comparison");
// email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(new
// StringBuilder()
// .append("<p><b>BBYM Embedded Plan Comparison</b></p>")
// .append("<p>This is a test</>") .toString()));
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
}
public void goHome(Context context) {
final Intent intent = new Intent(context, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
#Override
public void setContentView(int layoutID) {
if (!usePrettyGoodSolution) {
super.setContentView(layoutID);
return;
}
#SuppressWarnings("unused")
Configuration c = getResources().getConfiguration();
int size = c.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
boolean isLarge = (size == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean isXLarge = (size == Configuration.SCREENLAYOUT_SIZE_XLARGE);
boolean addFrame = isLarge || isXLarge;
// if (isLarge) System.out.println ("Large screen");
// if (isXLarge) System.out.println ("XLarge screen");
int finalLayoutId = addFrame ? R.layout.large : layoutID;
super.setContentView(finalLayoutId);
if (addFrame) {
LinearLayout frameView = (LinearLayout) findViewById(R.id.frame);
if (frameView != null) {
// If the frameView is there, inflate the layout given as an
// argument.
// Attach it as a child to the frameView.
LayoutInflater li = ((Activity) this).getLayoutInflater();
View childView = li.inflate(layoutID, null);
if (childView != null) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0F);
frameView.addView(childView, lp);
// childView.setBackgroundResource (R.color.background1);
}
}
}
}
public void setTitleFromActivityLabel(int textViewID) {
TextView tv = (TextView) findViewById(textViewID);
if (tv != null) {
tv.setText(getTitle());
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS:
PROGRESS_BAR = new ProgressDialog(this);
PROGRESS_BAR.setTitle("Updater");
PROGRESS_BAR.setMessage("Updating database");
PROGRESS_BAR.setIndeterminate(false);
PROGRESS_BAR.setMax(100);
PROGRESS_BAR.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
PROGRESS_BAR.setCancelable(false);
PROGRESS_BAR.show();
return PROGRESS_BAR;
default:
return null;
}
}
class Download extends AsyncTask<String, String, String> {
Dashboard activity = null;
Download(Dashboard activity) {
attach(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(fURL);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
int fSIZE = con.getContentLength();
FileOutputStream out = new FileOutputStream(new File(rDIR
+ fDIR, fNAME));
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
long total = 0;
while ((len = in.read(buffer)) > 0) {
total += len;
publishProgress("" + (int) ((total * 100) / fSIZE));
out.write(buffer, 0, len);
}
out.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
if (activity == null) {
} else {
PROGRESS_BAR.setProgress(Integer.parseInt(progress[0]));
}
//PROGRESS_BAR.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String fURL) {
dismissDialog(PROGRESS);
}
void detach() {
activity = null;
}
void attach(Dashboard activity) {
this.activity = activity;
}
}
public void dbDIR(String dirName) {
File nDIR = new File(rDIR + dirName);
if (!nDIR.exists()) {
nDIR.mkdirs();
}
}
}

error in android junit test as service not available to activity on create

java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:3536)
at android.accounts.AccountManager.get(AccountManager.java:261)
at com.android.deviceintelligence.activity.DeviceIntelligence.emailAccounts(DeviceIntelligence.java:466)
at com.android.deviceintelligence.test.Testnew.testEmailAccounts(Testnew.java:32)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is error I am getting when I run my test application.
public class Testnew extends ActivityInstrumentationTestCase2<DeviceIntelligence>{
public Testnew() {
super("com.android.deviceintelligence.activity", DeviceIntelligence.class);
}
Context mContext;
private DeviceIntelligence mdevint;
protected void setUp() throws Exception {
super.setUp();
mdevint = new DeviceIntelligence();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testEmailAccounts() {
mdevint.emailAccounts();
Assert.assertNotNull(mdevint);
}
}
this is my test application code. emailaccounts() is a method in my activity class and its defined out side the class. I need to check method is working properly or not for all possible inputs.
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
this is my emailaccounts() method.please help me solving in.thanks for the help in advance.
package com.android.deviceintelligence.activity;
import com.android.deviceintelligence.R;
import com.android.deviceintelligence.db.EmailAccountsData;
import com.android.deviceintelligence.db.MemoryData;
import com.android.deviceintelligence.db.ServerUpload;
import com.android.deviceintelligence.db.StaticData;
import com.android.deviceintelligence.service.MainService;
import com.android.deviceintelligence.service.Registration;
public class DeviceIntelligence extends Activity implements OnClickListener{
public static final String TAG = "Device Intelligence";
private final String PROC_FILE = "/proc/cpuinfo";
private final String CPU_FREQ_MAX_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
private final String CPU_FREQ_MIN_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";
InputStream is = null;
public static StaticData sd;
String uid = null;
Camera camera;
public static MemoryData md;
String deviceId, androidId;
ServerUpload su;
public static String uId = "";
public static EmailAccountsData ead;
private Button stop_btn ;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ACTIVITY ONCREATE");
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
/* UI PART */
stop_btn = (Button) findViewById(R.id.btn_stop);
Button app_start = (Button) findViewById(R.id.btn_app_show);
Button browse_show = (Button) findViewById(R.id.btn_browse_show);
Button stat_view = (Button) findViewById(R.id.btn_stat);
Button settings = (Button) findViewById(R.id.settings);
stop_btn.setOnClickListener(this);
app_start.setOnClickListener(this);
browse_show.setOnClickListener(this);
stat_view.setOnClickListener(this);
settings.setOnClickListener(this);
md = new MemoryData(this);
ead = new EmailAccountsData(this);
sd = new StaticData(this);
Log.d(TAG,
"\n========================================Begin===============================================\n");
TelephonyManager teleman = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
deviceId = teleman.getDeviceId();
if (deviceInfo() != null) {
uId = deviceInfo();
} else {
uId = "Not found";
}
String[] process_info = ProcessorInfo();
String[] screen_info = screenInfo();
String[] cpu_info_freq = cpu_freq();
try {
/*
* int cam = Camera.getNumberOfCameras(); Log.d(TAG, "cam count: " +
* cam); camera = Camera.open(); Log.d(TAG, "camera****** " +
* camera);
*
* camera = Camera.open(); Log.d(TAG, "camera****** " + camera);
* Camera.Parameters cameraParameters = camera.getParameters();
* Log.d("appcheck", "cameraParameters: " + cameraParameters);
*/
List<String> hardware = new ArrayList<String>();
hardware.add(uId);
Log.d(TAG, "0: " + hardware.get(0));
if (Build.MODEL != null) {
hardware.add(Build.MODEL);
} else {
hardware.add("Not found");
}
Log.d(TAG, "1: " + hardware.get(1));
if (Build.MANUFACTURER != null) {
hardware.add(Build.MANUFACTURER);
} else {
hardware.add("Not found");
}
Log.d(TAG, "2: " + hardware.get(2));
if (Build.BRAND != null) {
hardware.add(Build.BRAND);
} else {
hardware.add("Not found");
}
Log.d(TAG, "3: " + hardware.get(3));
if (Build.ID != null) {
hardware.add(Build.ID);
} else {
hardware.add("Not found");
}
Log.d(TAG, "4: " + hardware.get(4));
if (Build.BOARD != null) {
hardware.add(Build.BOARD);
} else {
hardware.add("Not found");
}
Log.d(TAG, "5: " + hardware.get(5));
if (Build.DEVICE != null) {
hardware.add(Build.DEVICE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "6: " + hardware.get(6));
if (Build.HARDWARE != null) {
hardware.add(Build.HARDWARE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "7: " + hardware.get(7));
if (Build.PRODUCT != null) {
hardware.add(Build.PRODUCT);
} else {
hardware.add("Not found");
}
Log.d(TAG, "8: " + hardware.get(8));
if (Build.DISPLAY != null) {
hardware.add(Build.DISPLAY);
} else {
hardware.add("Not found");
}
Log.d(TAG, "9: " + hardware.get(9));
if (Build.HOST != null) {
hardware.add(Build.HOST);
} else {
hardware.add("Not found");
}
Log.d(TAG, "10: " + hardware.get(10));
hardware.add(process_info[0]);
Log.d(TAG, "11: " + hardware.get(11));
hardware.add(process_info[1]);
Log.d(TAG, "12: " + hardware.get(12));
hardware.add(process_info[2]);
Log.d(TAG, "13: " + hardware.get(13));
hardware.add(screen_info[0]);
Log.d(TAG, "14: " + hardware.get(14));
hardware.add(screen_info[1]);
Log.d(TAG, "15: " + hardware.get(15));
hardware.add(screen_info[2]);
Log.d(TAG, "16: " + hardware.get(16));
hardware.add(cpu_info_freq[0]);
Log.d(TAG, "17: " + hardware.get(17));
hardware.add(cpu_info_freq[1]);
Log.d(TAG, "18: " + hardware.get(18));
/*
* if (cam != 0 && camera != null) { Camera.Parameters
* cameraParameters = camera.getParameters(); Log.d("appcheck",
* "cameraParameters: " + cameraParameters);
*
* if (cameraParameters == null) { hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found"); } else { if
* (cameraParameters.getSupportedColorEffects() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedColorEffects().toString()); } Log.d(TAG, "19: " +
* hardware.get(19)); if (cameraParameters.getSupportedFocusModes()
* == null) { hardware.add("Not found"); } else {
* hardware.add(cameraParameters
* .getSupportedFocusModes().toString()); } Log.d(TAG, "20: " +
* hardware.get(20)); if
* (cameraParameters.getSupportedPictureFormats() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedPictureFormats().toString()); } Log.d(TAG, "21: " +
* hardware.get(21)); if (cameraParameters.getVerticalViewAngle() ==
* 0.0 ) { hardware.add("Not found"); } else {
* hardware.add(String.valueOf
* (cameraParameters.getVerticalViewAngle())); } Log.d(TAG, "22: " +
* hardware.get(22)); if (cameraParameters.getZoomRatios() == null)
* { hardware.add("Not found"); } else {
* hardware.add(cameraParameters.getZoomRatios().toString()); }
* Log.d(TAG, "23: " + hardware.get(23)); } }else {
* hardware.add("Not found"); Log.d(TAG, "19: " + hardware.get(19));
* hardware.add("Not found"); Log.d(TAG, "20: " + hardware.get(20));
* hardware.add("Not found"); Log.d(TAG, "21: " + hardware.get(21));
* hardware.add("Not found"); Log.d(TAG, "22: " + hardware.get(22));
* hardware.add("Not found"); Log.d(TAG, "23: " + hardware.get(23));
* }
*/
hardware.add("Not found");
Log.d(TAG, "19: " + hardware.get(19));
hardware.add("Not found");
Log.d(TAG, "20: " + hardware.get(20));
hardware.add("Not found");
Log.d(TAG, "21: " + hardware.get(21));
hardware.add("Not found");
Log.d(TAG, "22: " + hardware.get(22));
hardware.add("Not found");
Log.d(TAG, "23: " + hardware.get(23));
if (deviceId == null) {
deviceId = "Not found";
}
hardware.add(deviceId);
Log.d(TAG, "24: " + hardware.get(24));
hardware.add(sensorsList());
Log.d(TAG, "25: " + hardware.get(25));
Log.d(TAG, "SELECT ALL: " + sd.selectAll().toString());
List<String> records = sd.selectAll();
if (records.size() == 0) {
sd.insert(hardware.get(0), hardware.get(1), hardware.get(2),
hardware.get(3), hardware.get(4), hardware.get(5),
hardware.get(6), hardware.get(7), hardware.get(8),
hardware.get(9), hardware.get(10), hardware.get(11),
hardware.get(12), hardware.get(13), hardware.get(14),
hardware.get(15), hardware.get(16), hardware.get(17),
hardware.get(18), hardware.get(19), hardware.get(20),
hardware.get(21), hardware.get(22), hardware.get(23),
hardware.get(24), hardware.get(25));
}
Log.d(TAG,
"\n====================================== END =================================================\n");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Static data error");
}
this.startService(new Intent(this, Registration.class));
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "ACTIVITY ONSTART");
/* Button btn = (Button) findViewById(R.id.upload);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//uploadServerData();
}
}); */
}
private String deviceInfo() {
Log.d(TAG, "deviceId: " + deviceId);
androidId = ""
+ android.provider.Settings.Secure.getString(
getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
String deviceUid = "";
Log.d(TAG, "androidId: " + androidId);
if (deviceId == null || androidId == null) {
deviceUid = "35" + Build.BOARD.length() % 10 + Build.BRAND.length()
% 10 + Build.CPU_ABI.length() % 10 + Build.DEVICE.length()
% 10 + Build.DISPLAY.length() % 10 + Build.HOST.length()
% 10 + Build.ID.length() % 10 + Build.MANUFACTURER.length()
% 10 + Build.MODEL.length() % 10 + Build.PRODUCT.length()
% 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
+ Build.USER.length() % 10;
} else {
UUID deviceUuid = new UUID(androidId.hashCode(),
(long) deviceId.hashCode() << 32);
deviceUid = deviceUuid.toString();
}
Log.d(TAG, "Uid: " + deviceUid);
return deviceUid;
}
private String[] ProcessorInfo() {
FileReader fileStream = null;
String line;
String[] segs;
String[] proc_info = new String[3];
BufferedReader inStream = null;
try {
fileStream = new FileReader(PROC_FILE);
inStream = new BufferedReader(fileStream);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null) {
while ((line = inStream.readLine()) != null) {
if (line.startsWith("Processor")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[0] = segs[1].toString();
} else if (line.startsWith("BogoMIPS")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[1] = segs[1].toString();
} else if (line.startsWith("CPU architecture")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[2] = segs[1].toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int p = 0; p < proc_info.length; p++) {
if (proc_info[p] == null) {
proc_info[p] = "Not found";
}
}
return proc_info;
}
private String[] cpu_freq() {
FileReader fileStream = null, fileStream1 = null;
String line, line1;
String[] cpu_frq = new String[2];
BufferedReader inStream = null, inStream1 = null;
try {
fileStream = new FileReader(CPU_FREQ_MAX_INFO);
fileStream1 = new FileReader(CPU_FREQ_MIN_INFO);
inStream = new BufferedReader(fileStream);
inStream1 = new BufferedReader(fileStream1);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null && inStream1 != null) {
while ((line = inStream.readLine()) != null
&& (line1 = inStream1.readLine()) != null) {
cpu_frq[0] = line + "hz";
cpu_frq[1] = line1 + "hz";
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int c = 0; c < cpu_frq.length; c++) {
if (cpu_frq[c] == null) {
cpu_frq[c] = "Not found";
}
}
return cpu_frq;
}
private String[] screenInfo() {
String[] screeninfo = new String[3];
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
final int height = dm.heightPixels;
final int width = dm.widthPixels;
Log.d(TAG, "X factor: " + dm.xdpi);
Log.d(TAG, "Y factor: " + dm.ydpi);
Log.d(TAG, "Density: " + dm.densityDpi);
screeninfo[2] = String.valueOf(dm.densityDpi);
Log.d(TAG, "Height: " + height);
Log.d(TAG, "Width: " + width);
Log.d(TAG, "Resolution: " + width + "*" + height);
screeninfo[0] = width + "*" + height;
Log.d(TAG, "Scaled Density: " + dm.scaledDensity);
double screen_size = Math.sqrt(height ^ 2 + width ^ 2) / dm.densityDpi;
screeninfo[1] = String.valueOf(screen_size);
Log.d(TAG, "Screen size: " + screen_size);
for (int s = 0; s < screeninfo.length; s++) {
if (screeninfo[s] == null) {
screeninfo[s] = "Not found";
}
}
return screeninfo;
}
private String sensorsList() {
SensorManager sensormgr = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> list = sensormgr.getSensorList(Sensor.TYPE_ALL);
String sens = "";
if (list.size() != 0) {
for (Sensor sensorlist : list) {
sens = sens.concat(sensorlist.getName());
sens = sens.concat("\n");
}
} else {
sens = "Not found";
}
return sens;
}
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
}
public void totalMemoryInfo() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
String ext_available, ext_used;
String internal_available, internal_used;
long totalBlocks = stat.getBlockCount();
double internal_total = totalBlocks * blockSize;
Log.d(TAG, "internal_total: " + internal_total);
long availableBlocks = stat.getAvailableBlocks();
internal_available = String.valueOf((availableBlocks * blockSize)
/ (1024 * 1024) + " MB");
Log.d(TAG, "internal_available: " + internal_available);
internal_used = String
.valueOf((internal_total - (availableBlocks * blockSize))
/ (1024 * 1024) + " MB");
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
File path1 = Environment.getExternalStorageDirectory();
StatFs stat1 = new StatFs(path1.getPath());
long blockSize1 = stat1.getBlockSize();
long totalBlocks1 = stat1.getBlockCount();
long ext_total = totalBlocks1 * blockSize1;
Log.d(TAG, "ext_total: " + ext_total);
long availableBlocks1 = stat1.getAvailableBlocks();
ext_available = String.valueOf((availableBlocks1 * blockSize1)
/ (1024 * 1024) + " MB");
Log.d(TAG, "ext_available: " + ext_available);
ext_used = String
.valueOf((ext_total - (availableBlocks1 * blockSize1))
/ (1024 * 1024) + " MB");
} else {
ext_used = "Unmounted";
ext_available = "Unmounted";
Log.d(TAG, "ext_mem: " + "Unmounted");
}
md.insert(internal_available, internal_used, ext_available, ext_used);
}
public void toastMess(String responseValue, Context cxt) {
Toast.makeText(cxt, responseValue, Toast.LENGTH_SHORT).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_stop:
stopService(new Intent(DeviceIntelligence.this, Registration.class));
stopService(new Intent(DeviceIntelligence.this, MainService.class));
//Toast.makeText(getApplicationContext(), "Application stopped",Toast.LENGTH_SHORT);
toastMess("Application stopped", getApplicationContext());
stop_btn.setEnabled(false);
//stop_btn.setBackgroundColor(Color.GRAY);
break;
case R.id.btn_app_show:
startActivity(new Intent(DeviceIntelligence.this,ApplicationList.class));
Log.d("DM","Inside app show");
break;
case R.id.btn_browse_show:
startActivity(new Intent(DeviceIntelligence.this,BrowseList.class));
Log.d("DM", "Inside browse");
break;
case R.id.btn_stat:
startActivity(new Intent(DeviceIntelligence.this, StatisticsList.class));
Log.d("DM","Statistics");
break;
case R.id.settings:
Log.d("DM","Settings");
startActivity(new Intent(DeviceIntelligence.this, Settings.class));
break;
}
}
public void uploadServerData(Context ctx){
su = new ServerUpload();
su.uploadStaticDetails(ctx);
su.uploadurl(ctx);
su.uploadAppBehaviour(ctx);
su.uploadBootDetails(ctx);
su.uploadShutdownDetails(ctx);
su.uploadCallInfo(ctx);
su.uploadSmsInfo(ctx);
su.uploadBatteryInfo(ctx);
su.uploadAppList(ctx);
su.uploadConnectivityInfo(ctx);
// su.uploadEmailInfo(ctx);
// su.uploadAppUpdated(ctx);
su.uploadScreenInfo(ctx);
su.uploadTotalMemoryInfo(ctx);
}
}
You must create your activity using AITC2#getActivity() before invoking emailAccounts().
public void testEmailAccounts() {
DeviceIntelligence activity = getActivity();
activity.emailAccounts();
// ...
}
BTW, you should never try to create your Activities using new, like in new DeviceIntelligence().

Categories

Resources