I want to use a switch: http://developer.android.com/guide/topics/ui/controls/togglebutton.html
to toggle something like Bluetooth which needs a prompt. The problem is when the user denies the action. If it's done just as shown in the example, the toggle will shown "on" even though the Bluetooth device is turned off, because the user denied. Is there a way to make the switch only show "on" if the user accepts the prompt and otherwise stay at "off"?
this is what I am trying to use the switch for:
Switch toggler = (Switch) findViewById(R.id.switch2);
toggler.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
final Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivityForResult(discoverableIntent, DISCOVERABLE_REQUEST);
} else {
// The toggle is disabled
final Intent stopDiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
stopDiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3);
startActivityForResult(stopDiscoverableIntent,DISCOVERABLE_REQUEST);
}
}
});
public void onActivityResult(int req_code, int res_code, Intent data){
System.out.println("Prior Check: " + res_code);
if(req_code==REQUEST_ENABLE_BT){
if(res_code==RESULT_OK){
Toast.makeText(getBaseContext(),"Bluetooth is now turned ON",Toast.LENGTH_SHORT).show();
System.out.println("BT Req.: " + res_code);
}
if(res_code==RESULT_CANCELED){
Toast.makeText(getBaseContext(),"Bluetooth enable totally failed bru!",Toast.LENGTH_SHORT).show();
System.out.println("BT Req.: " + res_code);
}
}
else if(req_code==DISCOVERABLE_REQUEST){
if (res_code==1){
toggle = true;
Toast.makeText(getBaseContext(),"Infinite discoverability enabled",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
}
if(res_code==3){
toggle = false;
Toast.makeText(getBaseContext(),"Discover mode ending",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
}
if(res_code==RESULT_CANCELED && toggle == true){
Toast.makeText(getBaseContext(),"Discover mode ending denied",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
//Switch sw = (Switch) findViewById(R.id.switch2);
//sw.setChecked(false);
}
if(res_code==RESULT_CANCELED && toggle == false){
Toast.makeText(getBaseContext(),"Infinite discoverability denied",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
//Switch sw = (Switch) findViewById(R.id.switch2);
//sw.setChecked(false);
}
}
}
Here once you press the switch you get a prompt for bluetooth, if you accept it does what it should do, but if I deny it still switches, which i would like it not to. I hope the question is more clear now.
You can use:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isEnabled())
{
//User accpeted keep toggle on or if off, programmatically turn on
}
else
{
//User rejected keep toggle off or if on, programmatically turn off
}
}
Related
Inside the BluetoothGattCallback method onConnectionStateChange I am checking for the successful connection with the BLE device and calling the discoverServices method afterwards. The BLE device needs a pin entry (prompt by Android) for an successful pairing. I want to discover all available services immediately after connecting to the device because when switching to the main activity of the application there should be data from the available characteristics already displayed.
I tried to analyze the functionality of the onConnectionStateChange method and the behavior of the BLE device with pin. Unfortunately the method is called once you initialize the connection and again after successfully entering the pin. There isn't a difference within the receiving state codes. Status and newState are exactly the same when initializing and after successful pin entry and connection. Therefore i added this workaround with the Thread.sleep method to wait for the user entry of the pin and call afterwards the discoverServices method. But this workaround is not very practical because the user need to enter the pin within these 10 seconds. If not the connection is successful but the services won't be discovered.
How can i check or differ between these two states? Initializing the connection and successful enter of the pin?
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d("KOPPLUNG", "In onConnectionStateChange with status: " + status + " and newState: " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
broadcastUpdate(ACTION_GATT_CONNECTED, mCallbackBleAddress);
Log.i(TAG, "Connected to GATT server." + mCallbackBleAddress);
// Attempts to discover services after successful connection.
try {
Thread.sleep(10000);
} catch (Exception e) {
}
for(int i = 0; i<5; i++){
if(mBoltDeviceHandler.getBoltDevice(mCallbackBleAddress).getBluetoothGatt().discoverServices()){
Log.i(TAG, "Attempting to start service discovery:" + true);
break;
}
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
switch (status){
case 0: Log.i(TAG, "Sucessfully Disconnected from GATT server.");
break;
case 133: // Handle internal Android Bug
Log.i(TAG, "Connection aborted, Android Error 133");
broadcastUpdate(ACTION_GATT_CONNECTION_NOT_SUCCESSFUL, mCallbackBleAddress);
break;
default: Log.i(TAG, "Unexpected Disconnection from GATT server. Errorcode: "+status);
broadcastUpdate(ACTION_GATT_DISCONNECTED, mCallbackBleAddress);
autoconnect(gatt.getDevice());
}
Addition
The code for building up the connection is divided up in three different classes. The application starts with an scan activity where available devices are being searched and listed. By clicking on one list item (device) the connection process will be started.
onListItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
Context mContext = getApplicationContext();
BoltDevice boltDevice = new BoltDevice(device,mContext);
int i = mBoltDeviceHandler.addBoltDevice(boltDevice);
Intent resultIntent = new Intent();
resultIntent.putExtra("IN_CONNECTION", boltDevice.getBleAddress());
resultIntent.putExtra("POSITION",i);
if(i != -1){
setResult(Activity.RESULT_OK, resultIntent);
}
else {
setResult(Activity.RESULT_CANCELED, resultIntent);
}
finish();
}
By running the above code an object from type BoltDevice is being created and added to the BoltDeviceHandler.
Relevant code from BoltDevice class
public BoltDevice(BluetoothDevice device, Context context) {
mContext = context;
this.mBluetoothDevice = device;
this.mBleAddress = device.getAddress();
this.mDeviceName = device.getName();
mBatteryLevel = 0;
mSpecialBolt = false;
//Workarround for 133 error taken from: https://github.com/googlesamples/android-BluetoothLeGatt/issues/44
mStartGattHandler.postDelayed(mStartGattRunnable, START_GATT_DELAY);
}
public void closeGatt() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
public boolean connect() {
// Previously connected device. Try to reconnect.
if (mBluetoothGatt != null) {
Log.d(TAG, "Trying to connect with existing bluetoothGATT to: " + mBleAddress);
if (mBluetoothGatt.connect()) {
return true;
} else {
Log.d(TAG, "Could not connect to existing bluetoothGATT: " + mBleAddress);
return false;
}
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothLeService.connect(mBluetoothDevice);
Log.d(TAG, "Trying to create a new connection to: " + mBluetoothDevice.getAddress());
return true;
}
public boolean disconnect() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
return true;
} else {
return false;
}
}
public void bindService(){
Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
}
Relevant code from the MainActivity (active after the ScanActivity is finished)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (5) : {
if (resultCode == Activity.RESULT_OK) {
int i = data.getIntExtra("POSITION",-1);
mReconnect[i] = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
updateText(i,true);
ToastCompat.makeText(MainActivity.this, "In Connection!", ToastCompat.LENGTH_SHORT).show();
}
}
});
}
if (resultCode == Activity.RESULT_CANCELED) {
if(data!=null) {
int i = mBoltDeviceHandler.getBoltDevicePositionInList(data.getStringExtra("IN_CONNECTION"));
mReconnect[i] = true;
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
ToastCompat.makeText(MainActivity.this, "In Connection!", ToastCompat.LENGTH_SHORT).show();
}
}
});
}
else{
ToastCompat.makeText(this,"No device selected!", ToastCompat.LENGTH_SHORT).show();
}
}
break;
}
}
}
(...)
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final String address = intent.getStringExtra(BluetoothLeService.EXTRA_ADDRESS);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
ToastCompat.makeText(MainActivity.this, mBoltDeviceHandler.getBoltDevice(address).getDeviceName() + " " + getResources().getString(R.string.BLE_Connected), ToastCompat.LENGTH_SHORT).show();
updateText(mBoltDeviceHandler.getBoltDevicePositionInList(address), false);
ToastCompat.makeText(MainActivity.this, mBoltDeviceHandler.getBoltDevice(address).getDeviceName()+ ": "+ getResources().getString(R.string.BLE_ServicesDiscovered), ToastCompat.LENGTH_SHORT).show();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
(...)
First of all, I would recommend using the Nordic library. That saved me a lot of headhacke when working with BLE on android and allow to keep a clean architecture.
You should have something of the state machine like :
connect to device
request GATT services / characteristic
request for the user code on Android
send user code
retrieve data over BLE
Also, after receiving a onConnection status change notifcation, you should xwait a few ms before starting discovering GATT
The onConnectionStateChange event is triggered just after the Android connects to a device.Moreover, when the device has Service Changed indication enabled, and the list of services has changed (e.g. using the DFU), the indication is received few hundred milliseconds later, depending on the connection interval. When received, Android will start performing a service discovery operation on its own, internally, and will NOT notify the app that services has changed.
public final void onConnectionStateChange(#NonNull final BluetoothGatt gatt,
final int status, final int newState) {
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
// Sometimes, when a notification/indication is received after the device got
// disconnected, the Android calls onConnectionStateChanged again, with state
// STATE_CONNECTED.
// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/43
if (bluetoothDevice == null) {
Log.e(TAG, "Device received notification after disconnection.");
log(Log.DEBUG, "gatt.close()");
try {
gatt.close();
} catch (final Throwable t) {
// ignore
}
return;
}
// Notify the parent activity/service
Log("Connected to " + gatt.Device.Address);
isConnected = true;
connectionState = State.Connected;
OnDeviceConnected(gatt.Device);
/*
* TODO: Please calculate the proper delay that will work in your solution.
* If your device does not use Service Change indication (for example does not have DFU) the delay may be 0.
*/
var delay = 1600; // around 1600 ms is required when connection interval is ~45ms.
postDelayed(() -> gatt.DiscoverServices(), delay);
} else {
if (newState == ProfileState.Disconnected)
{
var wasConnected = IsConnected;
if (gatt != null)
{
NotifyDeviceDisconnected(gatt.Device); // This sets the mConnected flag to false
if (_initialConnection) ConnectDevice(gatt.Device);
if (wasConnected || status == GattStatus.Success)
return;
}
}
/*
* Connection attempt did fail! Retry possible ?
*/
onError(gatt.Device, Error.LinkLost, status);
}
}
In my program, I have a switch, a text view and an accessibility service running.
When the switch is turned ON, the second screen opens from where I need to switch on my service and by doing this, the text in the first screen should change to ON(the text should change to ON only if the service is enabled).
But the problem is that the text in the first screen is changing to ON, as soon as I switch ON the switch, but before I enable my service from the second screen.
This is my code for the switch:
private void setSwitchAndText(){
boolean ifON;
ifON = isAccessibilitySettingsOn(getApplicationContext());
if(ifON) {
mySwitch.setChecked(true);
} else {
mySwitch.setChecked(false);
}
myTextview.setText(ifON ? R.string.on : R.string.off);
}
and this is how I check whether the service is enable or not:
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + myService.class.getCanonicalName();
boolean accessibilityFound = false;
try {
accessibilityEnabled = Settings.Secure.getInt(this.getContentResolver(),android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
Log.d(LOGTAG, "ACCESSIBILITY: " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
Log.d(LOGTAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
Log.d(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
Log.d(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
Log.d(TAG, "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
}
return accessibilityFound;
}
and this is the relevant code in the onCreate:
myTextview = (TextView) findViewById(R.id.my_text);
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setChecked(false);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myTextview.setText(isChecked ? R.string.on : R.string.off);
if (isChecked) {
askToStartAccessibilityService(getResources().getString(R.string.on));
} else {
askToStartAccessibilityService(getResources().getString(R.string.off));
}
}
});
The way your detecting active accessibility services is pretty intense and there's no reason for this. Try this code instead:
AccessibilityManager accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> serviceInfoList = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_SPOKEN);
return (serviceInfoList.size() > 0);
This post will be long because I'm trying to explain the full scenario of my problem. Please read it patiently.
Now, I'm trying to control the app features using some physical buttons connected to Arduino. To connect the Arduino to a mobile device I'm using an OTG cable.
I have three activities. One is a splash activity, which is launcher one. The other two are Activity1 and Activity2, in which I use this Arduino thing.
So now I've made a broadcast receiver for system actions i.e., USB Permission, USB Attached and USB Detached. I wrote the broadcast receiver in the activities itself separately. And I register the receiver when the activity is created i.e., in onCreate(). That goes for both the activities. And I unregister the receiver when the activity is destroyed.
In the broadcast receiver's onReceive() method, I write the code like this:
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
//Broadcast Receiver to automatically start and stop the Serial connection.
#Override
#AddTrace(name = "broadcast receiver", enabled = true/*Optional*/)
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
Toast.makeText(NewCameraActivity.this, String.valueOf(granted), Toast.LENGTH_SHORT).show();
device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
//Set Serial Connection Parameters.
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
Toast.makeText(NewCameraActivity.this, "Port Opening", Toast.LENGTH_SHORT).show();
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(NewCameraActivity.this, "PORT NOT OPEN", Toast.LENGTH_SHORT).show();
} else {
Log.d("SERIAL", "PORT IS NULL");
Toast.makeText(NewCameraActivity.this, "PORT IS NULLg", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(NewCameraActivity.this, "PERM NOT GRANTED", Toast.LENGTH_SHORT).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart();
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop();
finish();
}
};
};
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
String data;
try {
data = new String(arg0, "UTF-8");
final String finalData = data;
runOnUiThread(new Runnable() {
#Override
public void run() {
switch (finalData) {
case "portopen":
break;
case "portinc":
System.exit(0);
break;
case "scan":
onClickStop();
requestPicture();
break;
case "lang":
counter++;
counter = counter % 3;
if (counter == 0) {
ImageNameSingleton.getInstance().setLanguage("eng");
textToSpeech.speak("English selected", TextToSpeech.QUEUE_FLUSH, myHash1);
} else if (counter == 1) {
ImageNameSingleton.getInstance().setLanguage("hin");
textToSpeech.speak("Hindi Selected", TextToSpeech.QUEUE_FLUSH, myHash1);
} else if (counter == 2) {
ImageNameSingleton.getInstance().setLanguage("mar");
textToSpeech.speak("Marathi Selected", TextToSpeech.QUEUE_FLUSH, myHash1);
}
break;
default:
break;
}
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} //Defining a Callback which triggers whenever data is read.
};
#AddTrace(name = "onClickstart", enabled = true/*Optional*/)
public void onClickStart() {
Toast.makeText(NewCameraActivity.this, "onClickStart", Toast.LENGTH_SHORT).show();
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
Toast.makeText(NewCameraActivity.this, String.valueOf(deviceVID), Toast.LENGTH_SHORT).show();
if (deviceVID == 0x1A86) {
//Arduino Vendor ID
Toast.makeText(NewCameraActivity.this, "Device Found", Toast.LENGTH_SHORT).show();
Toast.makeText(NewCameraActivity.this, String.valueOf(deviceVID) + String.valueOf(device.getProductId()), Toast.LENGTH_SHORT).show();
PendingIntent pendingintent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
Toast.makeText(this, String.valueOf(usbManager.hasPermission(device)), Toast.LENGTH_SHORT).show();
usbManager.requestPermission(device, pendingintent);
keep = false;
connectionEstablished = true;
} else {
Toast.makeText(NewCameraActivity.this, "Device Not Found", Toast.LENGTH_SHORT).show();
connection = null;
device = null;
}
if (!keep) break;
}
}
}
private void onClickStop() {
if(serialPort!=null) serialPort.close();
else Toast.makeText(this, "No serial port", Toast.LENGTH_SHORT).show();
}
Here, when the device is connected to USB, the USB attached action is started and it will start to look for the devices and will search for a particular device with that vendorID. When it gets the device, it will start the USB Permission action to check the permission is given or not. If yes, the code in the USB permission action will be executed. If not, it will ask the user for permission.
Everything is the same for both activities.
Now in Activity1, after the serial port is opened, I will send a string by clicking a button and I receive it in the activity. Based on the string, a particular job will be done (as you can see it in the callback part). After the job (like clicking an image), the data will be sent to Activity2 and the Activity1 will be destroyed along with the receiver.
In Activity2, I will register the receiver again and I'm opening the port again and I'm getting the strings to do jobs.
This is the workflow. Now the problem is, I want the app to open (in the foreground), whether the app is in background or killed, when a button is clicked in Arduino. Also, the app should close when any other button is clicked.
How to do it? Is there any way? Or is my approach not correct? Anyone help me out...
Any help would be appreciated.
I'm trying to find a simple way to toggle on and off a devices Bluetooth discoverability on Android via a Checkbox. Switching it on is simple enough but I don't have any luck with turning if off again. I'm using a work around for by setting the device to discoverable for a second (a method I found on here on stackoverflow) but I need to find a way of doing it properly.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"No Bluetooth Support", Toast.LENGTH_SHORT).show();
} else {
if (mBluetoothAdapter.isEnabled()) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Device Discoverable", Toast.LENGTH_SHORT).show();
}
}
} else {
if (mBluetoothAdapter.isEnabled()) {
Intent disablediscoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
disablediscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(disablediscoverableIntent);
Toast.makeText(getApplicationContext(),
"Discoverable Disabled", Toast.LENGTH_SHORT).show();
}
}
I'm trying to create an app that scans for wifi. When the player does something in the game, it "consumes" the strongest wifi signal. That signal should no longer be detected on the next scan.
Anyone who's played Metal Gear Solid Portable ops would know what I mean.
I tried to do this by creating a List of Wireless Signals that have already been used by the player and can no longer be detected again. The problem is that after scanning the best network, I scan again and it still displays the same network instead of ignoring it.
public void onClick(View arg0) {
if (arg0.getId() == R.id.bStart) {
ActivityLoader.loadMain(this);
}
if (arg0.getId() == R.id.bScan) {
Toast.makeText(this, "Searching....", Toast.LENGTH_LONG).show();
for (ScanResult selectedSpot : networkList) {
{
if (firstSignal == null || checkIfNotUsed(firstSignal)) {
firstSignal = selectedSpot;
usedNetworks.add(firstSignal.SSID);
break;
}
}
}
}
if (firstSignal != null) {
Toast.makeText(
this,
"Found Food and Ammo at the " + firstSignal.SSID
+ " store.", Toast.LENGTH_LONG).show();
// textStatus.setText(usedNetworks.toString());
textStatus.setText(networkList.toString());
} else {
Toast.makeText(this, "Found nothing!!!", Toast.LENGTH_LONG).show();
}
}
private boolean checkIfNotUsed(ScanResult selectedSpot) {
// TODO Auto-generated method stub
boolean flag = true;
if (usedNetworks.isEmpty()) {
flag = true;
} else {
for (String used : usedNetworks) {
if (selectedSpot.SSID.equals(used)) {
flag = false;
break;
}
}
}
return flag;
}