Check Network and Internet Connection - Android - java

I was wondering if the method below check that I am both connected to a network, and can actually connected to the internet as well.
Not just connected to a network that won't let me access the internet ?
public boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
I think, it does but I am not 100% sure.
Thanks

On comparing the accepted answer on this post to your code, what you are doing should work. Feel free to compare code. The safest thing to do would be to run a few tests from airplane mode, with the WiFi turned off, and from a location away from WiFi just to be sure. Good luck.
Android - Programmatically check internet connection and display dialog if notConnected

Have a look into one of my old answers. It has two different methods
1. to check if a device is connected to a network
2. to check if a device is connected to Internet.

The code below will check the internet connectivity using kotlin in android studio:
private fun amIConnected(): Boolean {
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}

I tried the approach of user:3156908 but it kept crashing my app when the internet connection was off. Turns out there was a logical error on his code so i used the connectivityManager.getActiveNetworkInfo() != null to check for network details. In case the device is connected to the network or it is in the process of connecting to the network use the isConnectedOrConnecting()
In your AndroidManifest.xml file add the following
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Create a method called checkInternetConnection in your fragment class or Activity class and add the following lines of code.
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean checkInternetConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager) mcontext.getSystemService(mcontext.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
Then you can call the checkInternetConnection in your fragment's onViewCreated method or your activity's onCreate method.
Note
I would strongly advise you to test it the code when its connected to wifi, mobile data and airplane mode.

Related

How to back second activity to first activity if no internet connection/wifi/mobile data (JAVA_CODE)

I am beginner android developer... Recently I develop an apps. But I want If user device connected with wifi/mobile network and user open my apps automatically FirstActivity go to SecondActivity. In SecondActivity user can read a pdfBook/html/txt file. But when user Reading Pdfbook/html/txt file in SecondActivity and at the same time wifi/mobile network DISCONNECTED then SecondActivity automatically should come_back to FirstActivity. I try many way, but I fail to do that.... there is no resource in GoogleSearch for this problem. Please anybody help me.
public boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
this is the function that will return true if the network is connected
and return false if the network is not connected
if this function return true you go to next activty
if return false then what you want can do

Firebase Showing An Internal Error has occured. [7:]

I'm using Firebase as my cloud data in my android app. I'm using it's Firestore and Authentication feature. But when I try to signup it is showing me :
"An internal error has occurred. [7:]"
So, to solve this I came to search for the solution so I found that if I update the google_service.json file everything is going to be right. But When I updated it sometimes it is working and after some time it again shows me the same error.
I get this error while testing my app behavior when deliberately disabling my mobile internet connection and trying to login to my app using firebase Auth.
Try testing your network connectivity on Activity launch and display a toast
public static boolean getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return true;
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
Toast.makeText(context, "No network connection!", Toast.LENGTH_SHORT).show();
return false;
}
I had same problem with authentication via Firebase in my RN iOS project. After some research I found out that "Email/Password" Sign In/Up option was disabled. So I just turned it on. Hope it will help someone with similar issue.
https://i.stack.imgur.com/zoQ6g.png
Please check the internet connection of your device. I make the same mistake after internet connection enables it working.
Same error happened while I tried with network connection off and firebase authentication with email and password. for example,
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)... { ... }
If network connection is on, then it works fine.
make sure you run your emulator like this in vs Code
flutter emulators --launch Nexus_6_API_29 -dns-8.8.8.8
this will solve your problem

Restrict uses permission internet to a sole activity rather than the whole application

I am not that good with android manifest. Could someone tell me if it is possible to restrict this uses permission below to a sole activity rather the whole application itself. The reason I ask this is to prevent my app as a whole(aside from that one activity) to be not be reliant on the internet. Also if I were to remove this code from the manifest my activity that needs this would always crash on start.
<uses-permission android:name="android.permission.INTERNET"/>
I don't think you can add activity specific permissions. In fact, there doesn't exist a thing like activity specific permissions. Permissions are always defined at your application level.
What you should do is, check in your activities whether internet is available or not, and if it's not, write a separate flow so that your activity behaves normally.
Function to check if the device is connected :
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}

Failed to load map with markers in android 5.1.1

I have developed an android application with a map displaying markers on it with some information (requires android 4.0.3 and up).
Before releasing it I tested my app in most of the android OSs from 4.0.3 to 5 and I didn't face any issues.Today I tried to install my released app (from play store) in a tablet device with NEXUS 7 google and android verion 5.1.1. The app does not load my map at all message displayed "Application Stopped".
I tried an older private version of my app (in debug mode) in NEXUS 7 tablet and it was success with the only difference that I do not display toast messages. Toast message indicates if connection is available or not in user's device. This message is displayed on user's screen when map is loaded in order to inform user if connected or not to the internet. Please find below the code:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if (mobile == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTED)
{
Toast.makeText(getApplicationContext(),"Connection available",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"Connection not available",Toast.LENGTH_LONG).show();
}
Is the problem I had really related to the toast? Is the NEXUS 7 device blocking any try of connectivity manager to read the state of wi-fi or 3G from the device? So is the problem related to the security configuration applied on the device? Could you please help me to resolve this?
UPDATE CODE:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMan != null) {
//mobile
NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if (mobile == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTED)
{
Toast.makeText(getApplicationContext(),"Connection available",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"Connection not available",Toast.LENGTH_LONG).show();
}
} // end if
else
{ //do nothing
}
Add null checks for conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) and conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI), getNetworkInfo return null if connection type is not supported by the device.
From API Doc
a NetworkInfo object for the requested network type or null if the type is not supported by the device.
What I am guessing is Nexus 7 doesn't support sim card due to that it can throw NullPointerException.

phone hotspot does not detect its own access point in my application

I'm new in android programming and I don't know how to resolve in detecting access point of my phones hotspot. My application is to connect android devices via same access point, the problem is that whenever I start my phone hotspot, my application doesn't seem to read it as an access point. I want users to connect first in any access point(including my phones hotspot before going to the next activity. here's my code:
MainActivity.java
ImageButton class3 = (ImageButton) findViewById(R.id.multiplayer);
class3.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) { //whenever this button is click
WifiManager wifi = (WifiManager) context.getSystemService(WIFI_SERVICE);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (wifi.isWifiEnabled() || netInfo != null){ //connected in any access point(including own hotspot) then go to next activity
startActivity(new Intent(MainActivity.this.getBaseContext(), classmultiplayer.class));
}
else {
MainActivity.this.finish(); //to simplified the code i just used exit if its not connected to any acces point
}
}
});
Manifest
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
When I am connected to wifi, it works perfectly. but when I start my hotspot on my phone without any wifi connectivity it do "else statement" which is exit. I already tried some answers in stackoverflow and I don't think it solves my problem.
"just want to make sure that users are already connected to an access point before going to the next activity including its own hotspot, because I'm developing an offline multiplayer game and make them communicate with each other via same access points".
there is already an existing android application that can do this, I just want to apply it on my app. Please answer..

Categories