Updating textview data dynamically Android Java - java

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

Related

How to detect Network change and change activity from A to B when Network is connected

I have SplashActivity, Activity A and Activity B.
When the Internet is not available, Splash activity redirects to Activity A and when Internet is available and is connected SplashActivity redirects to Activity B.
I would like to immediately close the Activity A when user is connected itself and Open Activity B when user is still inside the app and he open his wifi or mobile Data.
Here is the code I'm using in SplahsActivity to redirect to Activity A and Activity B as per Network status
public static boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
and I check with
if (isNetworkStatusAvialable(getApplicationContext())) {
// Load Activity B
} else {
Load Activity A and Toast Message, " No Internet"
}
Thanks in advance.
In this case you should check network status using BroadcastReceiver because you immediately want to close current activity and move to other activity. So below is complete code for it:
ConnectivityStatusReceiver.java
public class ConnectivityStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
// Your code to start Activity B
Activity activity = (Activity) context;
intent = new Intent(activity, ActivityB.class);
activity.startActivity(intent);
} else {
Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectivityStatusReceiver connectivityStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivityStatusReceiver = new ConnectivityStatusReceiver();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityStatusReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (connectivityStatusReceiver != null) {
// unregister receiver
unregisterReceiver(connectivityStatusReceiver);
}
}
}
To close Activity A you just add android:noHistory="true" in Manifest like below:
<activity android:label="#string/app_name" android:name="ActivityA"/>
Hope this will help you.

Android: get a feedback when trying to connect to a wifi spot

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.

How to detect when user turn one wifi connection to other wifi?

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

Give a notificiation when you disconnect from a specific wifi network

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

Scanning available wifi, detect specific strongest Wifi SSID to launch an XML activity layout

I need to locate my current location in a building by scanning the strongest available Wifi to launch an activity. I want to locate only 3 places in that building. So if I am currently near any of those locations, I will click a button to scan the strongest available Wifi to launch an activity.
I need to scan available Wifi in a building.
Get the 3 strongest signal.
Then detect whether any of those 3 strongest signal's SSID is the same with the specific SSID that I want to locate.
If my SSID is one of the strongest 3 signals, then the application will launch a xml layout activity,
So far I already have the coding to scan strongest available Wifi. But I don't know how to launch an activity when the strongest specific Wifi SSID detected. I do not need the information about the Wifi, just to launch my activity layout that has my information.
At the moment I'm using the following bit of code to scan the strongest Wifi signal that I got from here:
WiFiDemo.java
public class WiFiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null)
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
wifi.startScan();
}
} }
WiFiScanReceiver.java
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
WiFiDemo wifiDemo;
public WiFiScanReceiver(WiFiDemo wifiDemo) {
super();
this.wifiDemo = wifiDemo;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifiDemo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
bestSignal = result;
}
String message = String.format("%s networks found. %s is the strongest.",
results.size(), bestSignal.SSID);
Toast.makeText(wifiDemo, message, Toast.LENGTH_LONG).show();
Log.d(TAG, "onReceive() message: " + message);
}
}
You just need to start your activity from onReceive. Unless I'm not understanding your question, you just need to fire off your activity.
Since you have the context on your receiver's onReceive you just need to startActivity()
Start Activity inside onReceive BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
Don't forget to define a proper filter for it in your manifest.
http://developer.android.com/reference/android/content/BroadcastReceiver.html

Categories

Resources