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