I am having a bit of trouble trying to utilize the default Android dialog for popping up networks listed in the area. I have done some research and tried different avenues, but I haven't found anything that works correctly.
WifiManager mWifiManager;
List<ScanResult> mScanResults;
WifiListAdapter wifiListAdapter;
TextView hiddenVersionNumber;
String connectedSSID = "";
ProgressBar wifiNetworksLoading;
ArrayList<WifiItem> networkList = new ArrayList<>();
private static final int WEAK_WIFI_SIGNAL_STRENGTH = 1;
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult>mScanResults = mWifiManager.getScanResults();
//*unregisterReceiver(mWifiScanReceiver);*//
Log.d(TAG, "bozo " + mScanResults.size());
//*networkList.clear();
if (wifiNetworksLoading != null) {
wifiNetworksLoading.setVisibility(View.GONE);
}*//
ArrayList<WifiItem> list = new ArrayList<>();
for (ScanResult scan : mScanResults) {
//*Log.d(TAG, "bozo3 " + scan.SSID);*//
int level = WifiManager.calculateSignalLevel(scan.level, 4);
boolean isConnected = false;
Log.d(TAG, "bozo2 " + connectedSSID);
if (!connectedSSID.isEmpty()) {
Log.d(TAG, "bozo2 " + connectedSSID + " = " + scan.SSID);
if (connectedSSID.equalsIgnoreCase(scan.SSID)) {
isConnected = true;
}
}
if (!scan.SSID.isEmpty()) {
networkList.add(new WifiItem(scan.SSID, scan.capabilities, level, isConnected));
}
}
The OnCreate code listed below...
mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//*registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));*//
mWifiManager.startScan();
if (mWifiManager != null) {
mWifiManager.setWifiEnabled(true); // turn on Wifi
}
Related
I am trying to read serial data from a USB device using my Samsung phone as the host. I have followed the USB Host Overview tutorial closely but I cannot get any data from the device. I am performing async read using UsbRequest as the device is continually streaming data I would like to read.
My Java code:
class TransferThread extends Thread {
private static final String TAG = "MainActivity";
private static int TIMEOUT = 5000;
private static int BUFFER_LENGTH = 32768;
private byte[] buffer = new byte[BUFFER_LENGTH];
UsbDeviceConnection connection;
UsbEndpoint endpoint;
TransferThread(UsbDeviceConnection connection, UsbEndpoint endpoint) {
this.connection = connection;
this.endpoint = endpoint;
}
public void run() {
Log.v(TAG, "New thread started");
UsbRequest usbRequest = new UsbRequest();
if(usbRequest.initialize(connection, endpoint)) {
Log.v(TAG, "USB request successfully initialised");
}
final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_LENGTH);
if(usbRequest.queue(byteBuffer)) {
Log.v(TAG, "USB request successfully queued");
}
if(connection.requestWait() == usbRequest) {
Log.v(TAG, "Successfully returned USB request result");
Log.v(TAG, "Has array: " + byteBuffer.hasArray());
Log.v(TAG, "Data: " + Arrays.toString(byteBuffer.array()));
Log.v(TAG, "Data: " + byteBuffer.toString());
}
else {
Log.v(TAG, "Failed to return USB request");
}
Log.v(TAG, "byteBuffer.ToString(): " + byteBuffer.toString());
/* int numBytesTransferred = connection.bulkTransfer(endpoint, buffer, buffer.length, TIMEOUT);
if(numBytesTransferred >= 0) {
Log.v(TAG, "Bulk transfer successful");
}
else {
Log.v(TAG, "Bulk transfer failed");
}*/
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
Log.v(TAG,"Permission granted for device");
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "Running Main activity onCreate");
// Enumerate USB devices
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Log.v(TAG, String.format("%d device(s) found by UsbManager", deviceList.size()));
for (HashMap.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
String key = entry.getKey();
Log.v(TAG, "Device name: " + key);
}
UsbDevice device = deviceList.get("/dev/bus/usb/002/002");
Log.v(TAG, "Device info: " + device.toString());
Log.v(TAG, String.format("Device has %d configuration(s)", device.getConfigurationCount()));
Log.v(TAG, String.format("Device has %d interface(s)", device.getInterfaceCount()));
// Obtain permission to communicate with a device
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, filter);
manager.requestPermission(device, permissionIntent);
int interfaceNumber = 0;
int endpointNumber = 0;
UsbInterface usbInterface = device.getInterface(interfaceNumber);
Log.v(TAG, String.format("Got interface %d", interfaceNumber));
Log.v(TAG, "Interface name: " + usbInterface.getName());
Log.v(TAG, "Interface class: Vendor specific " + usbInterface.getInterfaceClass());
UsbEndpoint endpoint = usbInterface.getEndpoint(endpointNumber);
Log.v(TAG, String.format("Got endpoint %d", endpointNumber));
int endpointType = endpoint.getType();
if(endpointType == UsbConstants.USB_ENDPOINT_XFER_CONTROL) {
Log.v(TAG, "Endpoint type: endpoint zero");
}
if(endpointType == UsbConstants.USB_ENDPOINT_XFER_ISOC) {
Log.v(TAG, "Endpoint type: isochronous endpoint");
}
if(endpointType == UsbConstants.USB_ENDPOINT_XFER_BULK) {
Log.v(TAG, "Endpoint type: bulk endpoint");
}
if(endpointType == UsbConstants.USB_ENDPOINT_XFER_INT) {
Log.v(TAG, "Endpoint type: interrupt endpoint");
}
int endpointDir = endpoint.getDirection();
if(endpointDir == UsbConstants.USB_DIR_IN) {
Log.v(TAG, "Endpoint direction: IN (device to host)");
}
if(endpointDir == UsbConstants.USB_DIR_OUT) {
Log.v(TAG, "Endpoint direction: OUT (host to device)");
}
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(usbInterface, true);
TransferThread thread = new TransferThread(connection, endpoint);
thread.start();
}
}
Using endpoint 0 (interrupt type) I get the following data when I run the code:
Results in Logcat
I'm not sure if I'm using requestWait incorrectly or if I'm using the wrong endpoint or some other USB setting. Any help would be appreciated, thanks!
Trying this...
public class MainActivity extends Activity {
PendingIntent mPermissionIntent;
Button btnCheck;
TextView textInfo;
UsbDevice device;
UsbManager manager;
private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.check);
textInfo = (TextView) findViewById(R.id.info);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
textInfo.setText("");
checkInfo();
}
});
}
public void startPrinting(final UsbDevice printerDevice) {
new Handler().post(new Runnable() {
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run() {
try {
Log.e("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = manager.openDevice(device);
conn.claimInterface(usbInterface, true);
String myStringData = "\nThis \nis \nmy \nsample \ntext";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request) {
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
} else {
Log.e("Info", "No request recieved");
}
// int transfered = conn.bulkTransfer(endPoint,
// myStringData.getBytes(),
// myStringData.getBytes().length, 5000);
// Log.i("Info", "Amount of data transferred : " +
// transfered);
} catch (Exception e) {
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally {
try {
conn.releaseInterface(usbInterface);
Log.e("Info", "Interface released");
conn.close();
Log.e("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.e("Info", "Brodcast reciever unregistered");
} catch (Exception e) {
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
private void checkInfo() {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
/*
* this block required if you need to communicate to USB devices it's
* take permission to device
* if you want than you can set this to which device you want to communicate
*/
// ------------------------------------------------------------------
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 i = "";
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
}
textInfo.setText(i);
if(!(i.equalsIgnoreCase("")))
{
startPrinting(device);
}
}
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) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
}
}
This code shows the device connected with OTG but Not Accepted as printer device to canon 2900b
Printer going in idle mode.
or phone got hanged
I'm trying to connect to random Bluetooth device that match a certain characteristic. I just want to print the incoming messages from the bluetooth device.
I've been trying for the past few days to try and connect to some random bluetooth device that matches a characteristic so that I'll be able to just print the messages from the bluetooth device.
public class main extends AppCompatActivity {
private List Service_UUIDs;
private List Charac_UUIDS;
private List Descriptor_UUIDs;
public static final UUID descriptor = UUID.fromString("863930fc-947c-421b-
9170-9969ea6ad610");
private BluetoothAdapter bluetoothAdapter = null;
private BluetoothLeScanner bluetoothLeScanner;
private ScanCallback scanCallback;
private TextView messageText;
private Handler handler;
private static final int SCAN_TIME = 15000;
private int connectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTED = 2;
private boolean isConnected;
private boolean isScanning;
private BluetoothLeScanner myScanner;
private BluetoothGatt bluetoothGatt;
private String connected = "";
public List<BluetoothGattService> myServices;
private ScanCallback myScanCallBack;
private BluetoothDevice myDevice;
private HashMap<String, BluetoothDevice> myScanResults;
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public static final int REQUEST_ENABLE_BT = 10;
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[])
null);
m.invoke(device, (Object[]) null);
Log.d("unpairDevice", Integer.toString(device.getBondState()));
}
catch (Exception e) { Log.e("unpairDevice", e.getMessage()); }
}
private void makeToast(String message) {
//creates pop-ups in UI of the message
Context context = getApplicationContext();
CharSequence text = message;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothManager bluetoothManager = (BluetoothManager)
getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if(!bluetoothManager.getAdapter().isEnabled()){
Intent btEnable = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btEnable, REQUEST_ENABLE_BT);
}
messageText = findViewById(R.id.atm_msg);
findViewById(R.id.scan_button).setOnClickListener(new handleScan());
}
class handleScan implements View.OnClickListener{
public void onClick(View view){
startScan();
}
}
private void startScan() {
List<ScanFilter> filters = new ArrayList<>();
ScanFilter scanFilter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(descriptor))
.build();
filters.add(scanFilter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build();
myScanResults = new HashMap<>();
myScanCallBack = new BtleScanCallback(myScanResults);
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
bluetoothLeScanner.startScan(myScanCallBack);
isScanning = true;
new Handler().postDelayed(this::stopScan, SCAN_TIME);
}
private void stopScan(){
if(isScanning && bluetoothAdapter != null
&& bluetoothAdapter.isEnabled()
&& bluetoothLeScanner != null){
bluetoothLeScanner.stopScan(myScanCallBack);
scanComplete();
}
myScanCallBack = null;
isScanning = false;
handler = null;
}
private void scanComplete(){
if (myScanResults.isEmpty()){
return;
}
for(BluetoothDevice device: myScanResults.values()){
connectDevice(device);
}
}
protected class BtleScanCallback extends ScanCallback {
private HashMap<String, BluetoothDevice> myScanResults;
BtleScanCallback(HashMap<String, BluetoothDevice> scanResults) {
myScanResults = scanResults;
}
#Override
public void onScanResult(int callbackType, ScanResult result) {
addScanResult(result);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult result : results) {
addScanResult(result);
}
}
#Override
public void onScanFailed(int errorCode) {
makeToast("BLE Scan Failed with code " + errorCode);
}
private void addScanResult(ScanResult result) {
myDevice = result.getDevice();
String deviceAddress = myDevice.getAddress();
myScanResults.put(deviceAddress, myDevice);
}
}
private void connectDevice(BluetoothDevice device) {
bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback);
}
private final BluetoothGattCallback bluetoothGattCallback = new
BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int
newState) {
super.onConnectionStateChange(gatt, status, newState);
if (status == gatt.GATT_FAILURE){
Log.d("BLE_Assistance", "-----> status: " + gatt.GATT_FAILURE);
disconnectGattServer();
return;
}
if (status == 133){
bluetoothAdapter.disable();
bluetoothAdapter.enable();
Log.d("OCSC: ", "133 GATT_ERROR OCCURRED");
}
if (newState == gatt.STATE_CONNECTED){
Log.d("BLE_Assistance", "-----> state: " +
gatt.STATE_CONNECTED);
connectionState = gatt.STATE_CONNECTED;
isConnected = true;
return;
}
else if (status != gatt.GATT_SUCCESS){
Log.d("BLE_Assistance", "-----> status: could not connect");
disconnectGattServer();
return;
}
else if (newState == gatt.STATE_DISCONNECTED){
Log.d("BLE_Assistance", "status: " + gatt.STATE_DISCONNECTED);
disconnectGattServer();
}
}
public void disconnectGattServer(){
isConnected = false;
connected = "";
if (bluetoothLeScanner != null && scanCallback != null){
bluetoothLeScanner.flushPendingScanResults(scanCallback);
}
if (!myScanResults.isEmpty()){
myScanResults.clear();
}
try {
if (myServices.isEmpty()){
Log.d("Services", "Empty");
}
else{
myServices.clear();
}
} catch (NullPointerException nullPointerException){
Log.d("Services", "" + nullPointerException);
}
bluetoothAdapter.cancelDiscovery();
if(bluetoothGatt != null){
bluetoothGatt.abortReliableWrite();
bluetoothGatt.disconnect();
bluetoothGatt.close();
bluetoothGatt = null;
Log.d("disconnect server", ": Disconnected GATT Server");
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
byte[] msg_bytes = characteristic.getValue();
try {
String message = new String(msg_bytes, 0, msg_bytes.length,
"utf-8");
Log.d("onCharacteristicRead", message);
new Handler(Looper.getMainLooper()).postDelayed(() -> {
makeToast("onCharacteristicRead: " + message);
messageText.append("\nonCharacteristicRead: " + message);
}, 1000);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status){
super.onServicesDiscovered(gatt,status);
Service_UUIDs = new ArrayList();
Charac_UUIDS = new ArrayList();
Descriptor_UUIDs = new ArrayList();
if(status != gatt.GATT_SUCCESS){
return;
}else{
myServices = gatt.getServices();
for (BluetoothGattService service : myServices) {
for (BluetoothGattCharacteristic charac : service.getCharacteristics()) {
if (charac.getUuid().toString().contains("863930fc")) {
Service_UUIDs.add(charac.getService().getUuid().toString());
Charac_UUIDS.add(charac.getUuid().toString());
Descriptor_UUIDs.add(descriptor);
BluetoothGattDescriptor desc = charac.getDescriptor(descriptor);
gatt.setCharacteristicNotification(charac, true);
desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(desc);
}
}
}
Log.d("BLE_Assistance", "------ UUID Lists: " + Service_UUIDs + Charac_UUIDS + Descriptor_UUIDs);
}
}
};
}
I am not completely sure, I am also struggling with this kind of project right now and I am quite new to programming on Android. But I spotted a small mistake in your startScan and stopScan codes
bluetoothLeScanner.startScan(myScanCallBack);
Should be
bluetoothLeScanner.startScan(List<ScanFilter> filters, ScanSettings settings, ScanCallback callback)
with your scan filters and settings.
When you only send 'myScanCallback' to your 'bluetoothLeScanner.startScan', you're sending only default parameters with no filters.
https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)
This means that you're searching for every device, and not specifically the one you want.
For testing while powerdraw isn't an issue, you can also set your ScanSettings to LOW_LATENCY (LOW_POWER is more intuitive to use with BLE but not a requirement. You can switch it later when you want more battery life while scanning).
I hope it helps you
I am trying to build an android application where I am using google cloud vision API for detecting faces. I am following this tutorial. The problem is that, I am unable to produce the toast message that was supposed to be displayed on the screen after I click the button but the logcat shows:
Attempt to invoke virtual method 'com.google.api.services.vision.v1.Vision$Images com.google.api.services.vision.v1.Vision.images()' on a null object reference
Here is the code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button upload_button;
private ImageView image_capture;
final int CAMERA_PIC_REQUEST = 100;
private Vision vision;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upload_button = (Button) findViewById(R.id.uploadb);
image_capture=(ImageView)findViewById(R.id.capturedImage);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
Vision.Builder visionBuilder = new Vision.Builder(
new NetHttpTransport(),
new AndroidJsonFactory(),
null);
visionBuilder.setVisionRequestInitializer(
new VisionRequestInitializer("AIzaSyAueQjrrY_GiXh7kNGlbDLKWhYP-4q77vI"));
Vision vision = visionBuilder.build();
upload_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);*/
imageDectection();
}
});
}
private void imageDectection() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
InputStream inputStream = getResources().openRawResource(R.raw.crewf);
byte[] photoData = IOUtils.toByteArray(inputStream);
Image inputImage = new Image();
inputImage.encodeContent(photoData);
Feature desiredFeature = new Feature();
desiredFeature.setType("FACE_DETECTION");
AnnotateImageRequest request = new AnnotateImageRequest();
request.setImage(inputImage);
request.setFeatures(Arrays.asList(desiredFeature));
BatchAnnotateImagesRequest batchRequest = new BatchAnnotateImagesRequest();
batchRequest.setRequests(Arrays.asList(request));
BatchAnnotateImagesResponse batchResponse =
vision.images().annotate(batchRequest).execute();
List<FaceAnnotation> faces = batchResponse.getResponses()
.get(0).getFaceAnnotations();
int numberOfFaces = faces.size();
String likelihoods = "";
for(int i=0; i<numberOfFaces; i++) {
likelihoods += "\n It is " +
faces.get(i).getJoyLikelihood() +
" that face " + i + " is happy";
}
final String message =
"This photo has " + numberOfFaces + " faces" + likelihoods;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
Log.d("ERROR", e.getMessage());
}
}
});
}
}
The picture is stored in /res/raw location as crewf.jpg. I have tried setting the types as LABEL_DETECTION,TEXT_DETECTION,LANDMARK_DETECTION but none of it works.
Can anyone help me in this?
You are not initializing the Vision object.
You should declare two class variables:
private Vision.Builder visionBuilder = new Vision.Builder(
new NetHttpTransport(),
new AndroidJsonFactory(),
null
).setVisionRequestInitializer(new VisionRequestInitializer(BuildConfig.GOOGLE_API_KEY));
private Vision vision;
Then on the onCreate build the object:
vision = visionBuilder.build();
After that, you're ready to go.
If you're still facing troubles email me, I could help you reviewing your code.
I am a new guy to android development. I have created a SMS Inbox application.
I managed to get the SMS Inbox of the phone. Now I want to set a onclick method to open a specific message in a new activity with the phone number and the message.
Here is the code for my inbox activity. I do not understand, the place to put my onclicklistitem method.
public class MessageInboxActivity extends ActionBarActivity implements OnItemClickListener {
private static MessageInboxActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static MessageInboxActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_inbox);
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.my_adapter_item, R.id.product_name, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
refreshSmsInbox();
}
public void refreshSmsInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
"\n" + smsInboxCursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (smsInboxCursor.moveToNext());
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can someone help me to start new activity with the phone number and the message.
I'd put this in a comment but I can't comment, can you clarify your problem? What activity are you trying to link to and what exactly do you want to achieve? it seems like you just need to add to your onItemClick()
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Intent in = new Intent(getApplicationContext,/*whatever activity you want to open*/);
in.putStringExtra(/*some static keystring*/,smsMessage);
startActivity(in);
but it's hard to say for sure without knowing more