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();
}
}
Related
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 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
}
}
i want to build an application using wifi direct to transfer files and i'm using NFC to reduce pairing time. I've already follow the instruction in http://developer.android.com/guide/topics/connectivity/wifip2p.html and http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html but my apps won't connect. and i took the code from wifi direct demo from android example.
when i trace the problem is when wifi direct broadcast receiver WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION the network info won't to connect with other device so, in my main class that implements ConnectionInfoListener that have a method onConnectionInfoAvailable it's never triggered.
can anyone help me? thx before
the code is like this
Wifi Direct BroadCast Receiver
`
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
activity.setIsWifiP2pEnabled(true);
} else {
activity.setIsWifiP2pEnabled(false);
//activity.resetData();
}
//Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (manager != null) {
}
//Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (manager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
manager.requestConnectionInfo(channel, activity);
} else {
// It's a disconnect
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
WifiP2pDevice device = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
activity.myname = device.deviceName + " " + device.deviceAddress + " " + device.primaryDeviceType + " " + device.secondaryDeviceType + " " + device.status;
}
}`
my main class
`
// how to connect
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = names[1];
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
connect(config);
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
}
});
}
public void disconnect() {
manager.removeGroup(channel, new ActionListener() {
#Override
public void onFailure(int reasonCode) {
//Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
Toast.makeText(getApplicationContext(), "Disconnect failed. Reason :" + reasonCode, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
public void onChannelDisconnected() {
// we will try once more
if (manager != null && !retryChannel) {
Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
//resetData();
retryChannel = true;
manager.initialize(this, getMainLooper(), this);
} else {
Toast.makeText(this,
"Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
Toast.LENGTH_LONG).show();
}
}
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
this.info = info;
// After the group negotiation, we can determine the group owner.
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Toast.makeText(getApplicationContext(), "Owner", Toast.LENGTH_SHORT).show();
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
Toast.makeText(getApplicationContext(), "Client", Toast.LENGTH_SHORT).show();
}
}
`
onConnectionInfoAvailable will never be executed because the networkInfo.isConnected() is never true.
Please help me.. Thx..
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;
}
I got a strange problem on restricting toast messages in OnReceive() of broadcast receiver
I have written code for displaying toast when wifi and bluetooth are enabled/disabled
but If I enable/disable wifi, toast for bluetooth also appearing and viceversa i.e all 4 toast messages appearing one by one when I enable/disable bluetooth and wifi
What I want to do is I want to show one toast when wifi is off/on and also for bluetooth individually
like
if WIFI is on - "wifi enabled"
if WIFI is off - "wifi disabled"
If bluetooth is on - "Bluetooth enabled"
If bluetooth is off - "Bluetooth disabled"
Only one toast at a time not all
How to get around this problem?
Here is my code
public class MyService extends BroadcastReceiver {
private WifiManager wifiManager;
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(wifiManager.isWifiEnabled()){
Toast.makeText(context.getApplicationContext(), "WIFI Enabled", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context.getApplicationContext(), "WIFI Disabled", Toast.LENGTH_LONG).show();
}
if(adapter.isEnabled()){
Toast.makeText(context.getApplicationContext(), "Bluetooth Enabled", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context.getApplicationContext(), " Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
Your Receiver is getting called whenever Wifi status is changed.And you showed Toast for Both Wifi and Bluetooth.So its showing Two toasts.Its not like that when Bluetooth is enabled or disabled Your wifi is None of enabled or disabled.Both wifi and bluetooth have enable or disable status.
To solve your problem you can try like
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
if(arg1.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLED||wifiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLING){
Toast.makeText(context.getApplicationContext(), "WIFI Enabled", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context.getApplicationContext(), "WIFI Disabled", Toast.LENGTH_LONG).show();
}
}else {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter.isEnabled()){
Toast.makeText(context.getApplicationContext(), "Bluetooth Enabled", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context.getApplicationContext(), " Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}
In your code you have two different if conditions, this is the only reason you are getting two Toast in display. look at my updated code here, it will solve your problem.
public class MyService extends BroadcastReceiver
{
private WifiManager wifiManager;
#Override
public void onReceive(Context context, Intent arg1)
{
// TODO Auto-generated method stub
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(wifiManager.isWifiEnabled() )
{
Toast.makeText(context.getApplicationContext(), "WIFI Enabled", Toast.LENGTH_LONG).show();
}
else if (!wifiManager.isWifiEnabled() )
{
Toast.makeText(context.getApplicationContext(), "WIFI Disabled", Toast.LENGTH_LONG).show();
}
else if(adapter.isEnabled() )
{
Toast.makeText(context.getApplicationContext(), "Bluetooth Enabled", Toast.LENGTH_LONG).show();
}
else if (!adapter.isEnabled() )
{
Toast.makeText(context.getApplicationContext(), " Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}