Check if connected to specific wifi on app start - java

When my app starts I want to check if the device is connected to a specific wifi, my current code looks like this
private boolean haveNetwork() {
boolean have_WIFI = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
for (NetworkInfo info:networkInfos) {
if (info.getTypeName().equalsIgnoreCase("WIFI" )) {
if (info.isConnected())
have_WIFI = true;
}
}
return have_WIFI;
}
But it only checks if the device has any WIFI connection at all. How would I modify it to check for a specific WIFI SSID e.g. "Home"?

Related

How do I perform network operation programmatically on WiFi and cellular data separately when both are connected in Android Studio?

This is the code that is used to connect to a screen with wifi on address 192.168.22.1.
It is working fine when connecting with mobile data turned off, but doesn't work if mobile data is on:
public void onConnectClicked(View view){
Y2Screen screen = new Y2Screen("http://192.168.22.1");
final TextView message=findViewById(R.id.mess);
try {
message.setText("Connecting....");
if (!screen.login("guest", "guest")) {
message.setText("Connection Failed");
} else {
message.setText("Done Loging.");
//VideoArea va = new VideoArea(0, 0, screen.getWidth(), screen.getHeight());
PicArea pa=new PicArea(0, 0, screen.getWidth(), screen.getHeight());
File dir = Environment.getExternalStorageDirectory();
String path = dir.getAbsolutePath();
//va.addVideo(path+"/glomo/image.jpeg", 100);
pa.addPage(path+"/glomo/test3.png","PNG");
ProgramPlayFile prog = new ProgramPlayFile(1);
prog.getAreas().add(pa);
String listId = screen.writePlaylist(new ProgramPlayFile[]{prog});
screen.play(listId);
}
} catch (Y2Exception e) {
e.printStackTrace();
}
}
Probably is because 192.168.22.1 is a local address, so it is only accessible from local network (wifi, ...). If you are using mobile connection data you are on the public internet so you will need to NAT that local address to a public address port.
You can detect the type of connection using:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
More info at Detect network connection type on Android and about NAT issue: Get the NAT translated IP and port of some local port and How to expose my localhost to the WWW? (port forwarding?)
If you have both connections active loop all the networks from connectivityManager.getAllNetworks() and choose one with connectivityManager.bindProcessToNetwork(network);
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
connectivityManager.bindProcessToNetwork(network);
break;
}
}
See Use multiple network interfaces in an app
I found out a solution for that and its working, we just need to change the network channel to transport through wifi instead of mobile internet.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final ConnectivityManager manager = (ConnectivityManager) MainActivity.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}

Android Firebase check connection status?

I have an App with the Firebase Realtime Database. This app should display a ProgressBar if it isn't connected. How can I do that? I tried it with ".info/connected", but the results seem pretty random. I need to check the connection to the online database, not the offline database. (basically, i want to disable offline capabilities, and show the user if they are offline)
var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com');
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
if (connectedSnap.val() === true)
{
/* we're connected! */
}
else {
/* Give a custom Toast / Alert dialogue and exit the application */
}
});
You can also add this check
public static boolean isNetworkAvailable(Context con) {
try {
ConnectivityManager cm = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Then check this in your Activity/Fragment
if (isNetworkAvailable)
{
//Do you task
}
else{
/*No internet so Give a custom Toast / Alert dialogue and exit the application */
}
Refer this link for more information
Some nicer check of network connection in kotlin:
val Context.isNetworkConnected
get() = (getSystemService(ContextWrapper.CONNECTIVITY_SERVICE) as ConnectivityManager)
.activeNetworkInfo?.isConnected ?: false

Force close window in Async task execute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Force close window, When Async task execute after connection is loss.
I'm tired using ConnectivityManager to check internet connection, because when device connect to wifi but no internet connection, ConnectivityManager showing is connected. can any body help me?
public boolean isConnected(){
boolean status=false;
ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
for (int i = 0; i<allNetworkInfo.length; i++){
if (allNetworkInfo[i].getState() == NetworkInfo.State.CONNECTED){
status = true;
}
}
return status;
}
you are almost done but need to check it also that network is connecting or connected.
public boolean isConnected(){
boolean status=false;
ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
for (int i = 0; i<allNetworkInfo.length; i++){
if (allNetworkInfo[i].isConnectedOrConnecting()){
status = true;
}
}
return status;
}
I Hope it helps you...
You can try this code to see if it works:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Try this code it works for me.
public static boolean isConnectedWithInternet(Context context) {
// return true;
boolean _isNetAvailable = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null) {
_isNetAvailable = wifiNetwork.isConnectedOrConnecting();
}
NetworkInfo mobileNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null) {
_isNetAvailable = mobileNetwork.isConnectedOrConnecting();
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
_isNetAvailable = activeNetwork.isConnectedOrConnecting();
}
// CGlobalVariables._isInternetOn = _isNetAvailable;
return _isNetAvailable;
}
You generally get an UnknownHostException when Internet is not reachable.
You should always check connected state before starting the request. But to handle connection loss during the process you can always catch UnknownHostException.

Internet Availability on Android

My problem is that my application have around 12-13 screen, and all of that uses internet to parse data. So if my application lost an internet connection, it should alert user with "no internet available" message.
Is there any built-in service or methods that check internet avilability in background and alert user if internet is not available?
You can use this function:
protected boolean isNetworkConnected() {
Context ctx = this;
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = cm.getActiveNetworkInfo();
if (network != null) {
return network.isAvailable();
}
return false;
}

How to detect if user has 3G/Wifi on before making URL connection?

I don't want my app to crash if the user doesn't have wifi or 3g connectivity. How can I catch this at runtime in my app?
First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device.
You'll need the ACCESS_NETWORK_STATE permission to use this service.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi.isConnected() == false && mMobile.isConnected() == false) {
showDialog(DIALOG_NETWORK_UNAVAILABLE);
}
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) is deprecated.
Below is an improved solution for the latest Android SDK.
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
boolean is3gEnabled = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connManager.getAllNetworks();
for(Network network: networks)
{
NetworkInfo info = connManager.getNetworkInfo(network);
if(info!=null) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
is3gEnabled = true;
break;
}
}
}
}
else
{
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mMobile!=null)
is3gEnabled = true;
}

Categories