how to set android hotspot active in background? - java

I'm working on app which will set hotspot on/off when button is clicked.
If i turn on hotspot with app, when i opened another app or got any notification hotspot automatically going to turn off
My code:
public class WifiAP extends Activity {
private static int constant = 0;
private static final int WIFI_AP_STATE_UNKNOWN = -1;
private static int WIFI_AP_STATE_DISABLING = 0;
private static int WIFI_AP_STATE_DISABLED = 1;
public int WIFI_AP_STATE_ENABLING = 2;
public int WIFI_AP_STATE_ENABLED = 3;
private static int WIFI_AP_STATE_FAILED = 4;
private final String[] WIFI_STATE_TEXTSTATE = new String[] {
"DISABLING","DISABLED","ENABLING","ENABLED","FAILED"
};
private WifiManager wifi;
private String TAG = "WifiAP";
private int stateWifiWasIn = -1;
private boolean alwaysEnableWifi = true; //set to false if you want to try and set wifi state back to what it was before wifi ap enabling, true will result in the wifi always being enabled after wifi ap is disabled
/**
* Toggle the WiFi AP state
* #param wifihandler
*/
public void toggleWiFiAP(WifiManager wifihandler, Context context) {
if (wifi==null){
wifi = wifihandler;
}
boolean wifiApIsOn = getWifiAPState()==WIFI_AP_STATE_ENABLED || getWifiAPState()==WIFI_AP_STATE_ENABLING;
new SetWifiAPTask(!wifiApIsOn,false,context).execute();
}
private int setWifiApEnabled(boolean enabled) {
Log.d(TAG, "*** setWifiApEnabled CALLED **** " + enabled);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "Aqual soul";
config.preSharedKey="aquasoul";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
//remember wirelesses current state
if (enabled && stateWifiWasIn==-1){
stateWifiWasIn=wifi.getWifiState();
}
/* //disable wireless
if (enabled && wifi.getConnectionInfo() !=null) {
Log.d(TAG, "disable wifi: calling");
wifi.setWifiEnabled(false);
int loopMax = 10;
while(loopMax>0 && wifi.getWifiState()!=WifiManager.WIFI_STATE_DISABLED){
Log.d(TAG, "disable wifi: waiting, pass: " + (10-loopMax));
try {
Thread.sleep(500);
loopMax--;
} catch (Exception e) {
}
}
Log.d(TAG, "disable wifi: done, pass: " + (10-loopMax));
}
*/
//enable/disable wifi ap
int state = WIFI_AP_STATE_UNKNOWN;
try {
Log.d(TAG, (enabled?"enabling":"disabling") +" wifi ap: calling");
wifi.setWifiEnabled(false);
Method method1 = wifi.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
//method1.invoke(wifi, null, enabled); // true
method1.invoke(wifi, config, enabled); // true
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
} catch (Exception e) {
Log.e(WIFI_SERVICE, e.getMessage());
// toastText += "ERROR " + e.getMessage();
}
//hold thread up while processing occurs
if (!enabled) {
int loopMax = 10;
while (loopMax>0 && (getWifiAPState()==WIFI_AP_STATE_DISABLING || getWifiAPState()==WIFI_AP_STATE_ENABLED || getWifiAPState()==WIFI_AP_STATE_FAILED)) {
Log.d(TAG, (enabled?"enabling":"disabling") +" wifi ap: waiting, pass: " + (10-loopMax));
try {
Thread.sleep(500);
loopMax--;
} catch (Exception e) {
}
}
Log.d(TAG, (enabled?"enabling":"disabling") +" wifi ap: done, pass: " + (10-loopMax));
//enable wifi if it was enabled beforehand
//this is somewhat unreliable and app gets confused and doesn't turn it back on sometimes so added toggle to always enable if you desire
if(stateWifiWasIn==WifiManager.WIFI_STATE_ENABLED || stateWifiWasIn==WifiManager.WIFI_STATE_ENABLING || stateWifiWasIn==WifiManager.WIFI_STATE_UNKNOWN || alwaysEnableWifi){
Log.d(TAG, "enable wifi: calling");
wifi.setWifiEnabled(true);
//don't hold things up and wait for it to get enabled
}
stateWifiWasIn = -1;
} else if (enabled) {
int loopMax = 10;
while (loopMax>0 && (getWifiAPState()==WIFI_AP_STATE_ENABLING || getWifiAPState()==WIFI_AP_STATE_DISABLED || getWifiAPState()==WIFI_AP_STATE_FAILED)) {
Log.d(TAG, (enabled?"enabling":"disabling") +" wifi ap: waiting, pass: " + (10-loopMax));
try {
Thread.sleep(500);
loopMax--;
} catch (Exception e) {
}
}
Log.d(TAG, (enabled?"enabling":"disabling") +" wifi ap: done, pass: " + (10-loopMax));
}
return state;
}
public int getWifiAPState() {
int state = WIFI_AP_STATE_UNKNOWN;
try {
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
} catch (Exception e) {
}
if(state>=10){
//using Android 4.0+ (or maybe 3+, haven't had a 3 device to test it on) so use states that are +10
constant=10;
}
//reset these in case was newer device
WIFI_AP_STATE_DISABLING = 0+constant;
WIFI_AP_STATE_DISABLED = 1+constant;
WIFI_AP_STATE_ENABLING = 2+constant;
WIFI_AP_STATE_ENABLED = 3+constant;
WIFI_AP_STATE_FAILED = 4+constant;
Log.d(TAG, "getWifiAPState.state " + (state==-1?"UNKNOWN":WIFI_STATE_TEXTSTATE[state-constant]));
return state;
}
class SetWifiAPTask extends AsyncTask<Void, Void, Void> {
boolean mMode; //enable or disable wifi AP
boolean mFinish; //finalize or not (e.g. on exit)
ProgressDialog d;
public SetWifiAPTask(boolean mode, boolean finish, Context context) {
mMode = mode;
mFinish = finish;
d = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
d.setTitle("Turning WiFi AP " + (mMode?"on":"off") + "...");
d.setMessage("...please wait a moment.");
d.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
d.dismiss();
MainActivity.updateStatusDisplay();
} catch (IllegalArgumentException e) {
};
if (mFinish){
finish();
}
}
#Override
protected Void doInBackground(Void... params) {
setWifiApEnabled(mMode);
return null;
}
}
}

Related

BLE CallBack onCharacteristicChanged is not call back

I am a student working with BLE, and I am not good at English, so please understand it with the help of Google Translator.
Since the BLE notification does not work during the work, it is difficult to attach the source, so please help.
boolean success4 = mBluetoothGatt.writeDescriptor(descriptor); is false but I don't know why.
// Debugging
private static final String TAG = "BleManager";
// Constants that indicate the current connection state
public static final int STATE_ERROR = -1;
public static final int STATE_NONE = 0; // Initialized
public static final int STATE_IDLE = 1; // Not connected
public static final int STATE_SCANNING = 2; // Scanning
public static final int STATE_CONNECTING = 13; // Connecting
public static final int STATE_CONNECTED = 16; // Connected
// Message types sent from the BluetoothManager to Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final long SCAN_PERIOD = 10000; // Stops scanning after a pre-defined scan period.
public static final long SCAN_INTERVAL = 5 * 60 * 1000;
// System, Management
private static Context mContext = null;
Handler mHandler;
private boolean connect = false;
// Bluetooth
private BluetoothAdapter mBluetoothAdapter;
private BluetoothManager mBluetoothManager;
private BluetoothGattCharacteristic mcharacteristic;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothDevice mDefaultDevice = null;
private BluetoothGatt mBluetoothGatt = null;
private ArrayList<BluetoothGattService> mGattServices
= new ArrayList<BluetoothGattService>();
private BluetoothGattService mDefaultService = null;
private ArrayList<BluetoothGattCharacteristic> mGattCharacteristics
= new ArrayList<BluetoothGattCharacteristic>();
private ArrayList<BluetoothGattCharacteristic> mWritableCharacteristics
= new ArrayList<BluetoothGattCharacteristic>();
private BluetoothGattCharacteristic mDefaultChar = null;
// Parameters
private int mState = -1;
private void BleManager() {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
//mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mContext = this;
if (mContext == null) {return;}
else
{
scanLeDevice(true);
}
}
public synchronized void finalize() {
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mState = STATE_IDLE;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
disconnect();
}
mDefaultDevice = null;
mBluetoothGatt = null;
mDefaultService = null;
mGattServices.clear();
mGattCharacteristics.clear();
mWritableCharacteristics.clear();
if (mContext == null)
return;
// Don't forget this!!
// Unregister broadcast listeners
// mContext.unregisterReceiver(mReceiver);
}
/*****************************************************
* Private methods
******************************************************/
/**
* This method extracts UUIDs from advertised data
* Because Android native code has bugs in parsing 128bit UUID
* use this method instead.
*/
private void stopScanning() {
if (mState < STATE_CONNECTING) {
mState = STATE_IDLE;
}
scanLeDevice(false);
//mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
/**
* Check services and looking for writable characteristics
*/
private int checkGattServices(List<BluetoothGattService> gattServices) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("# BluetoothAdapter", " not initialized");
return -1;
}
for (BluetoothGattService gattService : gattServices) {
// Default service info
Log.e("# GATT Service:", " " + gattService.getUuid().toString());
// Remember service
mGattServices.add(gattService);
// Extract characteristics
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
// Remember characteristic
mGattCharacteristics.add(gattCharacteristic);
for (BluetoothGattDescriptor descriptor:gattCharacteristic.getDescriptors()){
Log.e("# GATT Char:", gattCharacteristic.getUuid().toString());
Log.e(TAG, "BluetoothGattDescriptor: " + descriptor.getUuid().toString());
}
boolean isWritable = isWritableCharacteristic(gattCharacteristic);
if (isWritable) {
mWritableCharacteristics.add(gattCharacteristic);
}
boolean isReadable = isReadableCharacteristic(gattCharacteristic);
if (isReadable) {
readCharacteristic(gattCharacteristic);
}
if (isNotificationCharacteristic(gattCharacteristic) && gattCharacteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")) {
setCharacteristicNotification(gattCharacteristic, true);
if (gattCharacteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")) {
Log.e("default", "##############################################");
mDefaultChar = gattCharacteristic;
Log.e("default", "////////////////////////////////////////////// " + mDefaultChar.getUuid().toString());
//break;
}
}
}
}
return mWritableCharacteristics.size();
}
private boolean isWritableCharacteristic(BluetoothGattCharacteristic chr) {
if (chr == null) return false;
final int charaProp = chr.getProperties();
if (((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) |
(charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) > 0) {
Log.e("# Found writable", " characteristic");
return true;
} else {
Log.e("# Not writable", " characteristic");
return false;
}
}
private boolean isReadableCharacteristic(BluetoothGattCharacteristic chr) {
if (chr == null) return false;
final int charaProp = chr.getProperties();
if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
Log.e("# Found readable", " characteristic");
return true;
} else {
Log.e("# Not readable", " characteristic");
return false;
}
}
private boolean isNotificationCharacteristic(BluetoothGattCharacteristic chr) {
if (chr == null) return false;
final int charaProp = chr.getProperties();
if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
Log.e("# Found notification", " characteristic");
return true;
} else {
Log.e("# Not notification", " characteristic");
return false;
}
}
/**
* Request a read on a given {#code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {#code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* #param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("# BluetoothAdapter", " not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* Enables or disables notification on a give characteristic.
*
* #param characteristic Characteristic to act on.
* #param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("# BluetoothAdapter ", "not initialized");
return;
}
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
boolean success1 = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
//00002902-0000-1000-8000-00805f9b34fb
//public static String CLIENT_CHARACTERISTIC_CONFIG = "0000ffe1-0000-1000-8000-00805f9b34fb";
Log.e("info1",characteristic.getUuid().toString() + " // " + characteristic.getValue() + " // " + enabled + " // " + success1);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
Log.e("info2",characteristic.getUuid().toString() + " // " + characteristic.getValue() + " // " + enabled);
boolean success3 = descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean success2 = descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
Log.e("info3",characteristic.getUuid().toString() + " // " + characteristic.getValue() + " // " + enabled + " // " + success3 + " // " + success2);
//boolean success5 = mBluetoothGatt.writeCharacteristic(characteristic);
boolean success4 = mBluetoothGatt.writeDescriptor(descriptor);
Log.e("info4",descriptor.getCharacteristic() + " // " + descriptor.getValue() + " // " + descriptor.getPermissions() + " // " + descriptor.getUuid() + " // " + enabled + " // " + success4);
//mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
/*****************************************************
* Public methods
******************************************************/
public int getState() {
return mState;
}
private void scanLeDevice(final boolean enable) {
mHandler = new Handler();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(device.getName() != null && device.getName().equals("AINTEL_MFD") && connect == false){
connect = true;
scanLeDevice(false);
Log.e("ScanDevice",device.getName() + " // " + device.getUuids() + " // " + device.getAddress() + " // " + rssi + " // " + scanRecord[0] + " // " + scanRecord[1]);
connectGatt(Vars.mContext,false, device);
}
}
});
}
};
public boolean scanLeDevice(final boolean enable, UUID[] uuid) {
boolean isScanStarted = false;
if (enable) {
if (mState == STATE_SCANNING)
return false;
if (mBluetoothAdapter.startLeScan(uuid, mLeScanCallback)) {
mState = STATE_SCANNING;
mDeviceList.clear();
// If you want to scan for only specific types of peripherals
// call below function instead
//startLeScan(UUID[], BluetoothAdapter.LeScanCallback);
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
stopScanning();
}
}, SCAN_PERIOD);
isScanStarted = true;
}
} else {
if (mState < STATE_CONNECTING) {
mState = STATE_IDLE;
}
stopScanning();
}
return isScanStarted;
}
public boolean connectGatt(Context c, boolean bAutoReconnect, BluetoothDevice device) {
if (c == null || device == null)
return false;
mGattServices.clear();
mGattCharacteristics.clear();
mWritableCharacteristics.clear();
mBluetoothGatt = device.connectGatt(c, bAutoReconnect, mGattCallback);
mDefaultDevice = device;
mState = STATE_CONNECTING;
return true;
}
public boolean connectGatt(Context c, boolean bAutoReconnect, String address) {
if (c == null || address == null)
return false;
if (mBluetoothGatt != null && mDefaultDevice != null
&& address.equals(mDefaultDevice.getAddress())) {
if (mBluetoothGatt.connect()) {
mState = STATE_CONNECTING;
return true;
}
}
BluetoothDevice device =
BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
if (device == null) {
Log.e("# Device not found. ", "Unable to connect.");
return false;
}
mGattServices.clear();
mGattCharacteristics.clear();
mWritableCharacteristics.clear();
mBluetoothGatt = device.connectGatt(c, bAutoReconnect, mGattCallback);
mDefaultDevice = device;
mState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("# BluetoothAdapter", " not initialized");
return;
}
mBluetoothGatt.disconnect();
}
public boolean write(BluetoothGattCharacteristic chr, byte[] data) {
if (mBluetoothGatt == null) {
Log.e(TAG, "# BluetoothGatt not initialized");
return false;
}
BluetoothGattCharacteristic writableChar = null;
if (chr == null) {
if (mDefaultChar == null) {
for (BluetoothGattCharacteristic bgc : mWritableCharacteristics) {
if (isWritableCharacteristic(bgc)) {
writableChar = bgc;
}
}
if (writableChar == null) {
Log.e(TAG, "# Write failed - No available characteristic");
return false;
}
} else {
if (isWritableCharacteristic(mDefaultChar)) {
Log.e("# Default", "is PROPERY_WRITE | PROPERTY_WRITE_NO_RESPONSE");
writableChar = mDefaultChar;
} else {
Log.e("# De ", "is not writable");
mDefaultChar = null;
return false;
}
}
} else {
if (isWritableCharacteristic(chr)) {
Log.e("# user ", "GattCharacteristic is PROPERY_WRITE | PROPERTY_WRITE_NO_RESPONSE");
writableChar = chr;
} else {
Log.e("# user ", "GattCharacteristic is not writable");
return false;
}
}
writableChar.setValue(data);
writableChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
mBluetoothGatt.writeCharacteristic(writableChar);
mDefaultChar = writableChar;
return true;
}
public void setWritableCharacteristic(BluetoothGattCharacteristic chr) {
mDefaultChar = chr;
}
public ArrayList<BluetoothGattService> getServices() {
return mGattServices;
}
public ArrayList<BluetoothGattCharacteristic> getCharacteristics() {
return mGattCharacteristics;
}
public ArrayList<BluetoothGattCharacteristic> getWritableCharacteristics() {
return mWritableCharacteristics;
}
/*****************************************************
* Handler, Listener, Timer, Sub classes
******************************************************/
// Various callback methods defined by the BLE API.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mState = STATE_CONNECTED;
Log.e(TAG, "# Connected to GATT server.");
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mState = STATE_IDLE;
Log.e(TAG, "# Disconnected from GATT server.");
mBluetoothGatt = null;
mGattServices.clear();
mDefaultService = null;
mGattCharacteristics.clear();
mWritableCharacteristics.clear();
mDefaultChar = null;
mDefaultDevice = null;
}
}
#Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "# New GATT service discovered.");
checkGattServices(gatt.getServices());
} else {
Log.e(TAG, "# onServicesDiscovered received: " + status);
}
}
#Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// We've received data from remote
Log.e(TAG, "# Read characteristic11111: " + String.format("%02X",characteristic.getValue()));
/*
* onCharacteristicChanged callback receives same message
*
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
//for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
stringBuilder.append(data);
Log.e(TAG, stringBuilder.toString());
mHandler.obtainMessage(MESSAGE_READ, new String(data)).sendToTarget();
}
if(mDefaultChar == null && isWritableCharacteristic(characteristic)) {
mDefaultChar = characteristic;
}
*/
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
// We've received data from remote
byte[] newValue = characteristic.getValue();
Log.e(TAG, "# onCharacteristicChanged: " + String.format("%02X",newValue));
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
//for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
stringBuilder.append(data);
Log.e(TAG, stringBuilder.toString());
}
if (mDefaultChar == null && isWritableCharacteristic(characteristic)) {
mDefaultChar = characteristic;
}
}
};
}
3 things:
First make sure you have permissions. Requires Manifest.permission.BLUETOOTH permission.
Make sure your service/characteristic is correct.
Override onDescriptorWrite and check what you have done with writeDescriptor from there. If there is a problem, the onDescriptorWrite will tell you.
Google docs about BLE are not that good. Therefore, this amazing article will help you solve any issue with BLE.

How to print on a Canon LBP2900 or any printer using USB OTG?

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

AndroidWifiModule.java uses o r overrides a deprecated API

I downloaded react-native-android-wifi modules but when I run the code it says AndroidWifiModule.java uses o r overrides a deprecated API. Also its cannot connect to a network in android 8, so I added this line
//conf.SSID = String.format("\"%s\"", ssid);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
conf.SSID = ssid;
} else {
conf.SSID = "\"" + ssid + "\"";
}
is that true?
Here is the code :
public class AndroidWifiModule extends ReactContextBaseJavaModule {
//WifiManager Instance
WifiManager wifi;
ReactApplicationContext reactContext;
//Constructor
public AndroidWifiModule(ReactApplicationContext reactContext) {
super(reactContext);
wifi = (WifiManager)reactContext.getSystemService(Context.WIFI_SERVICE);
this.reactContext = reactContext;
}
//Name for module register to use:
#Override
public String getName() {
return "AndroidWifiModule";
}
//Method to load wifi list into string via Callback. Returns a stringified JSONArray
#ReactMethod
public void loadWifiList(Callback successCallback, Callback errorCallback) {
try {
List < ScanResult > results = wifi.getScanResults();
JSONArray wifiArray = new JSONArray();
for (ScanResult result: results) {
JSONObject wifiObject = new JSONObject();
if(!result.SSID.equals("")){
try {
wifiObject.put("SSID", result.SSID);
wifiObject.put("BSSID", result.BSSID);
wifiObject.put("capabilities", result.capabilities);
wifiObject.put("frequency", result.frequency);
wifiObject.put("level", result.level);
wifiObject.put("timestamp", result.timestamp);
//Other fields not added
//wifiObject.put("operatorFriendlyName", result.operatorFriendlyName);
//wifiObject.put("venueName", result.venueName);
//wifiObject.put("centerFreq0", result.centerFreq0);
//wifiObject.put("centerFreq1", result.centerFreq1);
//wifiObject.put("channelWidth", result.channelWidth);
} catch (JSONException e) {
errorCallback.invoke(e.getMessage());
}
wifiArray.put(wifiObject);
}
}
successCallback.invoke(wifiArray.toString());
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
//Method to force wifi usage if the user needs to send requests via wifi
//if it does not have internet connection. Useful for IoT applications, when
//the app needs to communicate and send requests to a device that have no
//internet connection via wifi.
//Receives a boolean to enable forceWifiUsage if true, and disable if false.
//Is important to enable only when communicating with the device via wifi
//and remember to disable it when disconnecting from device.
#ReactMethod
public void forceWifiUsage(boolean useWifi) {
boolean canWriteFlag = false;
if (useWifi) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
canWriteFlag = Settings.System.canWrite(reactContext);
if (!canWriteFlag) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + reactContext.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
reactContext.startActivity(intent);
}
}
if (((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && canWriteFlag) || ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))) {
final ConnectivityManager manager = (ConnectivityManager) reactContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager manager = (ConnectivityManager) reactContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
manager.bindProcessToNetwork(null);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ConnectivityManager.setProcessDefaultNetwork(null);
}
}
}
//Method to check if wifi is enabled
#ReactMethod
public void isEnabled(Callback isEnabled) {
isEnabled.invoke(wifi.isWifiEnabled());
}
//Method to connect/disconnect wifi service
#ReactMethod
public void setEnabled(Boolean enabled) {
wifi.setWifiEnabled(enabled);
}
//Send the ssid and password of a Wifi network into this to connect to the network.
//Example: wifi.findAndConnect(ssid, password);
//After 10 seconds, a post telling you whether you are connected will pop up.
//Callback returns true if ssid is in the range
#ReactMethod
public void findAndConnect(String ssid, String password, Callback ssidFound) {
List < ScanResult > results = wifi.getScanResults();
boolean connected = false;
for (ScanResult result: results) {
String resultString = "" + result.SSID;
if (ssid.equals(resultString)) {
connected = connectTo(result, password, ssid);
}
}
ssidFound.invoke(connected);
}
//Use this method to check if the device is currently connected to Wifi.
#ReactMethod
public void connectionStatus(Callback connectionStatusResult) {
ConnectivityManager connManager = (ConnectivityManager) getReactApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
connectionStatusResult.invoke(true);
} else {
connectionStatusResult.invoke(false);
}
}
//Method to connect to WIFI Network
public Boolean connectTo(ScanResult result, String password, String ssid) {
//Make new configuration
WifiConfiguration conf = new WifiConfiguration();
//clear alloweds
conf.allowedAuthAlgorithms.clear();
conf.allowedGroupCiphers.clear();
conf.allowedKeyManagement.clear();
conf.allowedPairwiseCiphers.clear();
conf.allowedProtocols.clear();
// Quote ssid and password
//conf.SSID = String.format("\"%s\"", ssid);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
conf.SSID = ssid;
} else {
conf.SSID = "\"" + ssid + "\"";
}
WifiConfiguration tempConfig = this.IsExist(conf.SSID);
if (tempConfig != null) {
wifi.removeNetwork(tempConfig.networkId);
}
String capabilities = result.capabilities;
// appropriate ciper is need to set according to security type used
if (capabilities.contains("WPA") || capabilities.contains("WPA2") || capabilities.contains("WPA/WPA2 PSK")) {
// This is needed for WPA/WPA2
// Reference - https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/wifi/java/android/net/wifi/WifiConfiguration.java#149
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.status = WifiConfiguration.Status.ENABLED;
conf.preSharedKey = String.format("\"%s\"", password);
} else if (capabilities.contains("WEP")) {
// This is needed for WEP
// Reference - https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/wifi/java/android/net/wifi/WifiConfiguration.java#149
conf.wepKeys[0] = "\"" + password + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else {
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks();
int updateNetwork = -1;
// Use the existing network config if exists
for (WifiConfiguration wifiConfig : mWifiConfigList) {
if (wifiConfig.SSID.equals(conf.SSID)) {
conf=wifiConfig;
updateNetwork=conf.networkId;
}
}
// If network not already in configured networks add new network
if ( updateNetwork == -1 ) {
updateNetwork = wifi.addNetwork(conf);
wifi.saveConfiguration();
}
// if network not added return false
if ( updateNetwork == -1 ) {
return false;
}
// disconnect current network
boolean disconnect = wifi.disconnect();
if ( !disconnect ) {
return false;
}
// enable new network
boolean enableNetwork = wifi.enableNetwork(updateNetwork, true);
if ( !enableNetwork ) {
return false;
}
return true;
}
//add configuration of hidden network and return it's networkId
public int setWifiConfig(String ssid, String sharedKey) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
conf.preSharedKey = "\"" + sharedKey + "\"";
conf.hiddenSSID = true;
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
return wifi.addNetwork(conf);
}
//Add a hidden wifi network and connect to it
//Example: wifi.connectToHiddenNetwork(ssid, password, (networkAdded) => {});
//Callback returns true if network added and tried to connect to it successfully
//It may take up to 15s to connect to hidden networks
#ReactMethod
public void connectToHiddenNetwork(String ssid, String password, Callback networkAdded) {
List<WifiConfiguration> list = wifi.getConfiguredNetworks();
int updateNetwork = -1;
// check if network config exists and it's hidden
for (WifiConfiguration wifiConfig : list) {
if (wifiConfig.SSID.equals("\"" + ssid + "\"") && wifiConfig.hiddenSSID) {
updateNetwork = wifiConfig.networkId;
}
}
// If network not already in configured networks add new network
if (updateNetwork == -1) {
updateNetwork = setWifiConfig(ssid, password);
}
// if network not added return false
if (updateNetwork == -1) {
networkAdded.invoke(false);
return;
}
// disconnect current network
boolean disconnect = wifi.disconnect();
if (!disconnect) {
networkAdded.invoke(false);
return;
}
// enable new network
boolean enableNetwork = wifi.enableNetwork(updateNetwork, true);
if (!enableNetwork) {
networkAdded.invoke(false);
return;
}
// reconnect to new network
boolean reconnect = wifi.reconnect();
if (!reconnect) {
networkAdded.invoke(false);
return;
}
wifi.saveConfiguration();
networkAdded.invoke(true);
}
//Disconnect current Wifi.
#ReactMethod
public void disconnect() {
wifi.disconnect();
}
//This method will return current ssid
#ReactMethod
public void getSSID(final Callback callback) {
WifiInfo info = wifi.getConnectionInfo();
// This value should be wrapped in double quotes, so we need to unwrap it.
String ssid = info.getSSID();
if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
ssid = ssid.substring(1, ssid.length() - 1);
}
callback.invoke(ssid);
}
//This method will return the basic service set identifier (BSSID) of the current access point
#ReactMethod
public void getBSSID(final Callback callback) {
WifiInfo info = wifi.getConnectionInfo();
String bssid = info.getBSSID();
callback.invoke(bssid.toUpperCase());
}
//This method will return current wifi signal strength
#ReactMethod
public void getCurrentSignalStrength(final Callback callback) {
int linkSpeed = wifi.getConnectionInfo().getRssi();
callback.invoke(linkSpeed);
}
//This method will return current wifi frequency
#ReactMethod
public void getFrequency(final Callback callback) {
WifiInfo info = wifi.getConnectionInfo();
int frequency = info.getFrequency();
callback.invoke(frequency);
}
//This method will return current IP
#ReactMethod
public void getIP(final Callback callback) {
WifiInfo info = wifi.getConnectionInfo();
String stringip = longToIP(info.getIpAddress());
callback.invoke(stringip);
}
//This method will remove the wifi network as per the passed SSID from the device list
#ReactMethod
public void isRemoveWifiNetwork(String ssid, final Callback callback) {
List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks();
for (WifiConfiguration wifiConfig : mWifiConfigList) {
String comparableSSID = ('"' + ssid + '"'); //Add quotes because wifiConfig.SSID has them
if(wifiConfig.SSID.equals(comparableSSID)) {
wifi.removeNetwork(wifiConfig.networkId);
wifi.saveConfiguration();
callback.invoke(true);
return;
}
}
callback.invoke(false);
}
#ReactMethod
public void reScanAndLoadWifiList(Callback successCallback, Callback errorCallback) {
WifiReceiver receiverWifi = new WifiReceiver(wifi, successCallback, errorCallback);
getCurrentActivity().registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi.startScan();
}
#ReactMethod
public void getDhcpServerAddress(Callback callback) {
DhcpInfo dhcpInfo = wifi.getDhcpInfo();
String ip = longToIP(dhcpInfo.serverAddress);
callback.invoke(ip);
}
public static String longToIP(int longIp){
StringBuffer sb = new StringBuffer("");
String[] strip=new String[4];
strip[3]=String.valueOf((longIp >>> 24));
strip[2]=String.valueOf((longIp & 0x00FFFFFF) >>> 16);
strip[1]=String.valueOf((longIp & 0x0000FFFF) >>> 8);
strip[0]=String.valueOf((longIp & 0x000000FF));
sb.append(strip[0]);
sb.append(".");
sb.append(strip[1]);
sb.append(".");
sb.append(strip[2]);
sb.append(".");
sb.append(strip[3]);
return sb.toString();
}
private WifiConfiguration IsExist(String SSID) {
List<WifiConfiguration> existingConfigs = wifi.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
class WifiReceiver extends BroadcastReceiver {
private Callback successCallback;
private Callback errorCallback;
private WifiManager wifi;
public WifiReceiver(final WifiManager wifi, Callback successCallback, Callback errorCallback) {
super();
this.successCallback = successCallback;
this.errorCallback = errorCallback;
this.wifi = wifi;
}
// This method call when number of wifi connections changed
public void onReceive(Context c, Intent intent) {
c.unregisterReceiver(this);
try {
List < ScanResult > results = this.wifi.getScanResults();
JSONArray wifiArray = new JSONArray();
for (ScanResult result: results) {
JSONObject wifiObject = new JSONObject();
if(!result.SSID.equals("")){
try {
wifiObject.put("SSID", result.SSID);
wifiObject.put("BSSID", result.BSSID);
wifiObject.put("capabilities", result.capabilities);
wifiObject.put("frequency", result.frequency);
wifiObject.put("level", result.level);
wifiObject.put("timestamp", result.timestamp);
} catch (JSONException e) {
this.errorCallback.invoke(e.getMessage());
return;
}
wifiArray.put(wifiObject);
}
}
this.successCallback.invoke(wifiArray.toString());
return;
} catch (IllegalViewOperationException e) {
this.errorCallback.invoke(e.getMessage());
return;
}
}
}
}

Problems with Out of memory error

I get out of memory error if the function doesWifiExist is false if it is true every thing works normally.Can someone tell me what m i doing wrong
The idea is to get a list of wifi networks nearby and check if the inserted network exists in the list.
Here is the wifi network scanning code and the the function that checks if the wifi network exists.
MainActivity:
private WiFiConnection _wifiConnection = null;
static final int MY_PERMISSIONS_REQUEST = 1042;
private static final String PERMISSIONS_TAG = "PERMISSION";
...
#Override
protected void onStart() {
super.onStart();
_wifiConnection = new WiFiConnection(this);
startScan();
}
#Override
protected void onStop() {
super.onStop();
_wifiConnection.stopScan();
unregisterReceiver(_wifiScanReceiver);
}
void startScan() {
checkPermission(this);
registerReceiver(_wifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Thread t = new Thread(_wifiConnection.getWifiScanner());
t.start();
}
private final BroadcastReceiver _wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
if (_wifiConnection != null && _wifiConnection.isWifiEnabled()) {
_wifiConnection.updateScanData();
}
}
}
};
public static boolean checkPermission(Activity activity) {
boolean permission = true;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> requiringList = new ArrayList<>();
permission = activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "ACCESS_COARSE_LOCATION: " + permission);
if (!permission) {
requiringList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (requiringList.size() > 0) {
String[] stringArray = requiringList.toArray(new String[0]);
activity.requestPermissions(stringArray, MY_PERMISSIONS_REQUEST);
}
}
return permission;
}
private boolean doesWifiExist(String s){
String[] array = s.split(" ");
String ssid = array[0];
boolean flag = false;
//Check if wifi exists in the area
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
return flag;
}
WiFiConnection class:
public class WiFiConnection
{
private static final int SCAN_INTERVAL = 5000;
final private List<String> _listSSIDs = new ArrayList<>();
private WifiManager _wifiManager;
private final WiFiScanner _startScan = new WiFiScanner();
private List<ScanResult> scanResults;
WiFiConnection(Activity activity) {
_wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
//Puts wifi networks in a list
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
WiFiScanner getWifiScanner() { return _startScan; }
void stopScan() { _startScan.stop(); }
boolean isWifiEnabled() { return _wifiManager.isWifiEnabled(); }
//Gets the wifi networks
void updateScanData() {
if ((_wifiManager != null && _wifiManager.isWifiEnabled())) {
scanResults = _wifiManager.getScanResults();
}
}
//Scans at an interval
private class WiFiScanner implements Runnable
{
private boolean _stop = false;
public void stop() {_stop = true;}
#Override
public void run() {
while (!_stop) {
_listSSIDs.clear();
_wifiManager.startScan();
try {
Thread.sleep(SCAN_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
The code where doesWifiExist is used.
//Check if wifi exists in the area
if(doesWifiExist(barcode.displayValue)){
//Connects to wifi
WifiConnect(barcode.displayValue);
//Saves item in db
insertItem();
if(networkSecurity.equals("None")){
networkPass = empty;
}
//Adds item to recyclerview
historyItems.add(0, new HistoryItem(wifiName + " " + networkSSID, wifiPass + " " + networkPass));
adapter.notifyItemInserted(0);
} else
Snackbar.make(findViewById(R.id.main_activity), R.string.snackInvalidQrCode, Snackbar.LENGTH_SHORT).show();
This method is called many times, and it everytime adds all scanResults at the end of field _listSSIDS.
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
Use a local variable with a new List or better Set there.
Instead replace
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
with
flag = _wifiConnection.hasSSID(String ssid);
public boolean hasSSID(String ssid) {
for (int i = 0; i < scanResults.size(); i++) {
if (ssid.equals(scanResults.get(i).SSID)) {
return true;
}
}
return false;
}

Phonegap : BluetoothChatExample [Android]

I try to develop a minimalistic BluetoothChat for Android with Phonegap. The Plugin is based on the Android SDK Example of the BluetoothChat as you can see in the example code.
The native BluetoothChat works fine.
The Problem is, when i call my "write"-Function, the "ConnectedThread" is always null, although the connection is established.
I can't recognize where it is set to null again, after the State was set to 3 (STATE_CONNECTED).
So when i run the program native on android, it works fine and the state during write is always 3, but when i use my phonegap plugin 'r'(ConnectedThread) becomes null :
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
Log.i(TAG, "State "+mState);
if (mState != STATE_CONNECTED) return;
Log.i(TAG, "Connected Thread "+mConnectedThread);
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
I used a lot of debug messages, but i was never informed that the state is null again.
Full source code :
PLUGIN.java
public class BluetoothConnection extends CordovaPlugin {
//Android specific tag-messages
private static final String TAG ="BluetoothConnection";
private static final boolean D = true;
// Member-Variables
public BluetoothAdapter mBluetoothAdapter;
public JSONArray mListOfDiscoveredDevices;
public String mConnectedDeviceName;
public ConnectionHandler mConnectionHandler;
// Phonegap-specific actions, which call the function
public String ACTION_ENABLEBLUETOOTH = "enableBluetooth";
public String ACTION_DISABLEBLUETOOTH = "disableBluetooth";
public String ACTION_DISCOVERDECIVES = "discoverDevices";
public String ACTION_STOPDISCOVERDEVICES = "stopDiscoverDevices";
public String ACTION_CREATEBOND = "createBond";
public String ACTION_WRITEMESSAGE = "writeMessage";
// not usable, this moment
public String ACTION_DISCONNECT = "disconnect";
//Message types sent from the ConnectionHandler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
#Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.equals(null)) {
Log.i(TAG, "no adapter was found");
}
mConnectionHandler = new ConnectionHandler(mHandler);
if (action.equals(ACTION_ENABLEBLUETOOTH)) {
enableBluetooth();
}
else if (action.equals(ACTION_DISABLEBLUETOOTH)) {
disableBluetooth();
}
else if (action.equals(ACTION_DISCOVERDECIVES)) {
discoverDevices();
}
else if (action.equals(ACTION_STOPDISCOVERDEVICES)) {
stopDiscovering(callbackContext);
}
else if (action.equals(ACTION_CREATEBOND)) {
try {
BluetoothDevice remoteBtDevice = createBond(args, callbackContext);
connect(remoteBtDevice, callbackContext);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(action.equals(ACTION_WRITEMESSAGE)){
writeMessage(args.getString(0));
}
else if (action.equals(ACTION_DISCONNECT)) {
disconnect();
}
return false;
}
public void enableBluetooth() {
if (!mBluetoothAdapter.equals(null)) {
mBluetoothAdapter.enable();
Log.i(TAG, "bluetooth on");
}
}
public void disableBluetooth() {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
Log.i(TAG, "bluetooth off");
}
}
public void discoverDevices() {
mListOfDiscoveredDevices = new JSONArray();
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
cordova.getActivity().registerReceiver(mFoundDevices, intentFilter);
mBluetoothAdapter.startDiscovery();
}
private void stopDiscovering(CallbackContext callbackContext) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
PluginResult res = new PluginResult(PluginResult.Status.OK,
mListOfDiscoveredDevices);
res.setKeepCallback(true);
callbackContext.sendPluginResult(res);
Log.i("Info", "Stopped discovering Devices !");
}
public BluetoothDevice createBond(JSONArray args, CallbackContext callbackContext) throws Exception {
String macAddress = args.getString(0);
Log.i(TAG, "Connect to MacAddress "+macAddress);
BluetoothDevice btDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
Log.i("Device","Device "+btDevice);
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
if(btDevice.equals(null))
throw new NullPointerException("Remote BluetoothDevice could not be paired !");
return btDevice;
}
public void removeBond(BluetoothDevice btDevice) throws Exception {
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
}
public void connect(BluetoothDevice btDevice, CallbackContext callbackContext) {
if(!btDevice.equals(null)){
mConnectionHandler.connect(btDevice, false);
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
Log.i(TAG, "Status after connecting "+mConnectionHandler.getState());
}
else {
callbackContext.error("Could not connect to "+btDevice.getAddress());
}
}
public void disconnect(){
}
public void writeMessage(String message){
if(mConnectionHandler.getState() != ConnectionHandler.STATE_CONNECTED){
Log.i(TAG, "Could not write to device");
Log.i(TAG, "State "+mConnectionHandler.getState());
}
if(message.length() > 0) {
byte[] send = message.getBytes();
mConnectionHandler.write(send);
Log.i(TAG, "sending "+message);
}
else {
Log.i(TAG, "There is nothing to send.");
}
}
private BroadcastReceiver mFoundDevices = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "found Device !", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("FOUND", "Name " + device.getName() + "-" + device.getAddress());
JSONObject discoveredDevice = new JSONObject();
try {
discoveredDevice.put("name", device.getName());
discoveredDevice.put("adress", device.getAddress());
if (!isJSONInArray(discoveredDevice)) {
mListOfDiscoveredDevices.put(discoveredDevice);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case ConnectionHandler.STATE_CONNECTED:
Log.i(TAG, "ConnectionHandler.STATE_CONNECTED !");
break;
case ConnectionHandler.STATE_CONNECTING:
Log.i(TAG, "ConnectionHandler.STATE_CONNECTING !");
break;
case ConnectionHandler.STATE_LISTEN:
Log.i(TAG, "ConnectionHandler.STATE_LISTEN !");
break;
case ConnectionHandler.STATE_NONE:
Log.i(TAG, "ConnectionHandler.STATE_NONE !");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
Log.i(TAG, "Write "+writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.i(TAG, "Read "+readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Log.i(TAG, mConnectedDeviceName);
break;
case MESSAGE_TOAST:
String message = msg.getData().getString(TOAST);
Log.i(TAG, "Connection lost : " +message);
break;
}
}
};}
CONNECTION-HANDLER
public class ConnectionHandler {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";
// Unique UUID for this application
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public ConnectionHandler(Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(BluetoothConnection.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() {
return mState;
}
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
setState(STATE_LISTEN);
// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null) {
mSecureAcceptThread = new AcceptThread(true);
mSecureAcceptThread.start();
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread(false);
mInsecureAcceptThread.start();
}
}
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device, final String socketType) {
if (D) Log.d(TAG, "connected, Socket Type:" + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(BluetoothConnection.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothConnection.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
setState(STATE_NONE);
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
Log.i(TAG, "State "+mState);
if (mState != STATE_CONNECTED) return;
Log.i(TAG, "Connected Thread "+mConnectedThread);
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothConnection.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothConnection.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
ConnectionHandler.this.start();
}
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothConnection.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothConnection.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
ConnectionHandler.this.start();
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private String mSocketType;
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure":"Insecure";
// Create a new listening server socket
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
if (D) Log.d(TAG, "Socket Type: " + mSocketType +
"BEGIN mAcceptThread" + this);
setName("AcceptThread" + mSocketType);
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (ConnectionHandler.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),
mSocketType);
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
}
public void cancel() {
if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (ConnectionHandler.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothConnection.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
ConnectionHandler.this.start();
break;
}
}
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothConnection.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}}
Thanks !!!
I implemented again in a new project - now it works, don't know why - but it work now.

Categories

Resources