I am working on an android application in which i have created a list with WiFi spots and under them two fields(ssid field and a password field) and a connect button.
the app
My problem is, when i fill up the 2 fields and click the connect button, i want to take a feedback if the phone connect to the wifi spot that i am trying to, or if the password is wrong. So that i can print a toast if it was connected or entered the wrong password.
**when the password is wrong, phone connect instantly to the previous wifi spot.
the code i use when the button pressed
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\""+ ssidField.getText().toString() +"\"";
wifiConfiguration.preSharedKey = "\""+ passwordField.getText().toString() +"\"";
int netId = wifiManager.addNetwork(wifiConfiguration);
if (netId >= 0) {
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
myBroadcastReceiver = new MyBroadcastReceiver(connectionsList, wifiManager,
emptyListText, ssidField, passwordField);
ssidField.setText("");
passwordField.setText("");
}
the code i use in the broadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo.State state = networkInfo.getState();
// i use logs for testing
switch (state) {
case CONNECTING:
Log.i(TAG, "CONNECTING");
break;
case CONNECTED:
Log.i(TAG, "CONNECTED");
break;
case SUSPENDED:
Log.i(TAG, "SUSPENDED");
break;
case DISCONNECTED:
Log.i(TAG, "DISCONNECTED");
break;
case DISCONNECTING:
Log.i(TAG, "DISCONNECTING");
break;
}
}
How can i got a feedback when the phone connect to wifi that i enter?
Refer to this. How to use SUPPLICANT_STATE_CHANGED_ACTION WiFi BroadcastReceiver - android and this too https://developer.android.com/reference/android/net/wifi/SupplicantState.
Related
I have problem with WiFi connection detection. My goal is to detect when user is switching between different WiFis. I found this, but it only detects when WiFi was established. In my case I need to know when one WiFi network changed to another on phone.
You can use BroadcastReceiver
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
if(netInfo.isConnected()) {
WifiManager wifiManager = (WifiManager) context.getAplicationContext().getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
Log.d("Wifi Connected", "Wifi name is "+ info.getSSID());
}
}
}
}
I implemented the code to check wifi state connected or not. I made a text view
TextView WifiTv = (TextView) findViewById(R.id.wifistate);
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiCheck = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
It works but it does not update dynamically and therefore if I turn off wifi I have to refresh the activity for the textview to change (not data binded). How can I make the textview update without refresh please? Thx
EDIT: I have this code in a seperate class which works well with a toast. All I want to do is display in textview instead. How can I connect the textview variable to this class which does not have xml please?
public void onReceive(Context context, Intent intent) {
NetworkInfo info =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info != null && info.isConnected()) {
// Do your work.
// e.g. To check the Network Name or other info:
WifiManager wifiManager = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Toast.makeText(context, "Connected to: " + ssid,
Toast.LENGTH_SHORT).show();
}
You required BroadcastReceiver and wifimanager. BroadcastReceiver which start when app launches to receive the the implicit intent every time. wifimanager to to check the status.
did you try to add a onResume function to check again each time you resume yout activity?
Don't know your app but maybe this,
#Override
protected void onResume() {
super.onResume();
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
}
If your others variables are not global to Activity, create them again within the onResume
I am writing an Android app. In my app, I want it to scan the WiFi network, and then connect to a dedicated Access Point (AP) by checking the SSID. And then after connected to the AP, establish a TCP connection to it.
Above I have described 3 tasks in order. I know how to do each task independently, however I do not know the proper way to finish them in sequence. Examples are appreciated.
Currently my code is to start scan the WiFi network whenever the user pressed a button by:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi is enabled", Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
I used a broadcast receiver to check when the scanning finished, and then invoke a method ( ReconnectAP() ) to connect WiFi to the AP. I also used the broadcast receiver to check when it connected to the AP, then I want to execute an Async Task to establish the TCP network. However, by googling, I learn that it is a bad practice to execute async task in a broadcast receiver, because the async task can be killed by Android when the receiver finished.
private String networkSSID = "The_AP_SSID";
// In onCreate of MainActivity, register the broadcast receiver:
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION));
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Implement my broadcast receiver class:
BroadcastReceiver WiFireceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is SCAN_RESULTS_AVAILABLE_ACTION");
Log.d(TAG, "Start to check if need to reconnect to Charger AP");
ReconnectAP();
}
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is NETWORK_STATE_CHANGED_ACTION");
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
// If the connection type is WiFi...
if (netInfo != null && ConnectivityManager.TYPE_WIFI == netInfo.getType()) {
// If it is connected now....
if (netInfo.isConnected()) {
Log.d(TAG, "WiFi connected");
// Get WiFi connection information, eg SSID
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "WiFi connected SSID is : " + ssid);
if(ssid.equals(networkSSID)) {
// Start async task to establish a TCP connection:
new ConnectTCPAsynTask().execute();
}
} else {
Log.d(TAG, "WiFi disconnected");
}
}
}
}
};
int ReconnectAP() {
Log.d(TAG, "In ReconnectAP( )");
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "Original connected AP SSID: " + ssid);
if (!ssid.equals(networkSSID)) {
Log.d(TAG, "It is not equal to the dedicated AP SSID,
we will disconnect the current WiFi connection,
and then connect to our dedicate AP");
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
Log.d(TAG, "Start disconnect and reconnect to " + networkSSID);
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
return 1;
}
}
Log.d(TAG,"Reach here if cannot find the target SSID");
return -1;
}
Log.d(TAG, "Reach here if we already connected to the dedicated AP");
return 0;
}
Pass a flag from the broadcast receiver back to the main activity and let the main activity handle the task.
I need my application to give a notification whenever a specific WiFi goes offline.
I got it to give a notification every time the WiFi connection disconnects. But I need it to only give a notification when a specific WiFi network disconnects. Is my code suitable for this? I read something about class wifiinfo, is this the solution?
My question is, how do I alter the code to only give a notification when a specific WiFi goes offline? Any help in the right direction would be nice! Some examples would be even more awesome.
Thanks in advance!
(Eventually I need a button and when you press this the specific wifi your on atm will become that specific wifi when you disconnect from it you get a notification. If that makes sense.)
The code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_hoofdmenu);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(!isNetworkConnectionAvailable(context)){
showNotification();
}
}
};
public static boolean isNetworkConnectionAvailable(Context context)
{
boolean isNetworkConnectionAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null)
{
isNetworkConnectionAvailable = activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED;
}
return isNetworkConnectionAvailable;
}
To detect SSID changes, listen for WifiManager.NETWORK_STATE_CHANGED_ACTION, grab the SSID from the intent extra WifiManager.EXTRA_BSSID.
See: Execute code when wifi SSID changes
I'm trying to assess my phones ability to connect to my wifi network. I want to figure out how long it takes to authenticate to my wifi access point, how long it is taking to obtain an IP address, etc..
I've made a lot of progress thanks to this website and lots of testing. However I can never seam to be able to get my broadcast receiver to trigger off certain connection states. I would really like to get somehow detect the time when authentication occurs.
Now I know what the Android documentation says and the Authentication state should be an easy thing to access. However in practice with multiple devices, that state is never reached. I've even tried polling with the following code.
public void start(long delayMillsec) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
long timeout = System.currentTimeMillis() + 5000;
running = true;
while(true)
{
int oldState = state;
showWifiStatus();
int newState = state;
if(newState != oldState)
{
Log.e("STATE", stateString + ": " + System.nanoTime());
}
}
} }
, delayInMillsec);
}
public void showWifiStatus() {
boolean connected = false;
boolean associated = false;
ConnectivityManager connManager = (ConnectivityManager) thisContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
DetailedState val = mWifi.getDetailedState();
if (val == NetworkInfo.DetailedState.SCANNING) {
//Log.e("Detailed Wifi Info"," wifi state is SCANNING ");
state = 0;
stateString = "SCANNING";
}
if (val == NetworkInfo.DetailedState.CONNECTING) {
//Log.e("Detailed Wifi Info"," wifi state is CONNECTING ");
associated = true;
state = 1;
stateString = "CONNECTING";
}
if (val == NetworkInfo.DetailedState.AUTHENTICATING) {
//Log.e("Detailed Wifi Info"," 3wifi state is AUTHENTICATING");
associated = true;
state = 2;
stateString = "AUTHENTICATING";
}
if (val == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
//Log.e("Detailed Wifi Info"," wifi state is OBTAINING_IPADDR");
associated = true;
state = 3;
stateString = "OBTAINING_IPADDR";
}
if (val == NetworkInfo.DetailedState.CONNECTED) {
//Log.e("Detailed Wifi Info"," wifi state is CONNECTED ");
connected = true;
associated = true;
state = 4;
stateString = "CONNECTED";
}
if (val == NetworkInfo.DetailedState.DISCONNECTED) {
//Log.e("Detailed Wifi Info"," wifi state is DISCONNECTED ");
state = 5;
stateString = "DISCONNECTED";
}
if (val == NetworkInfo.DetailedState.DISCONNECTING) {
// Log.e("Detailed Wifi Info"," wifi state is DISCONNECTING ");
state = 6;
stateString = "DISCONNECTING";
}
if (val == NetworkInfo.DetailedState.FAILED) {
//Log.e("Detailed Wifi Info"," wifi state is FAILED");
state = 7;
stateString = "FAILED";
}
if (val == NetworkInfo.DetailedState.IDLE) {
//Log.e("Detailed Wifi Info"," wifi state is IDLE");
state = 8;
stateString = "IDLE";
}
if (val == NetworkInfo.DetailedState.SUSPENDED) {
//Log.e("Detailed Wifi Info"," wifi state is SUSPENDED");
state = 9;
stateString = "SUSPENDED";
}
}
Where I call the start function immediately from a background service, then I walked around between known wifi AP's and disconnected the wifi and reconnected etc...
I've also tried the connectivity receiver to pick up whatever I could.
I used this intent filter:
IntentFilter ConnectedFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
ConnectedFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
ConnectedFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
ConnectedFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
getApplicationContext().registerReceiver(ConnectedToAPReceiver,
ConnectedFilter);
With this receiver, to output absolutely EVERYTHING that was being received. And there was never any indication that the authentication state is ever triggered.
private BroadcastReceiver ConnectedToAPReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();
if (extras != null) {
Log.e("NEW Action", intent.getAction());
for (String key: extras.keySet()) {
Log.e("CONN_ACTION", "key [" + key + "]: " +
extras.get(key));
}
Log.e("NEW THING", "------------");
}
else {
Log.e("CONNACTION", "no extras");
}
}};
I'm using the following permissions too:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
Are there any Android experts out there who can help me on this one? Ideally I would like to get some working code that I can use, but even some good information on why this state never does get reached would be very helpful. Is this a bug?
Thanks!
It works for me:
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(receiverWifi, mIntentFilter);
class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent intent) {
String action = intent.getAction();
if(action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)){
Log.d("WifiReceiver", ">>>>SUPPLICANT_STATE_CHANGED_ACTION<<<<<<");
SupplicantState supl_state=((SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE));
switch(supl_state){
case ASSOCIATED:Log.i("SupplicantState", "ASSOCIATED");
break;
case ASSOCIATING:Log.i("SupplicantState", "ASSOCIATING");
break;
case AUTHENTICATING:Log.i("SupplicantState", "Authenticating...");
break;
case COMPLETED:Log.i("SupplicantState", "Connected");
break;
case DISCONNECTED:Log.i("SupplicantState", "Disconnected");
break;
case DORMANT:Log.i("SupplicantState", "DORMANT");
break;
case FOUR_WAY_HANDSHAKE:Log.i("SupplicantState", "FOUR_WAY_HANDSHAKE");
break;
case GROUP_HANDSHAKE:Log.i("SupplicantState", "GROUP_HANDSHAKE");
break;
case INACTIVE:Log.i("SupplicantState", "INACTIVE");
break;
case INTERFACE_DISABLED:Log.i("SupplicantState", "INTERFACE_DISABLED");
break;
case INVALID:Log.i("SupplicantState", "INVALID");
break;
case SCANNING:Log.i("SupplicantState", "SCANNING");
break;
case UNINITIALIZED:Log.i("SupplicantState", "UNINITIALIZED");
break;
default:Log.i("SupplicantState", "Unknown");
break;
}
int supl_error=intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
if(supl_error==WifiManager.ERROR_AUTHENTICATING){
Log.i("ERROR_AUTHENTICATING", "ERROR_AUTHENTICATING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
}
}
<receiver
android:name=".MyActivity$WifiReceiver"
android:process=":remote" >
</receiver>