App stops when implementing ConnectivityManager and NetworkInfo - java

For my app, I was trying to detect when the user is connected to the internet. This is one of the methods I've been using, although I've used some other that where basically the same, but using other methods of the objects used:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
return false;
}
Even if this does not lead to any compilation error, when launching the app it stops abruptly and does not respond. I'd like to know why this happens and how to solve it or, if has no aparent solution, if there's another way of doing what I wanted.
I have tried deleting part of the code strategically and I have noticed that the part that gives problems is netInfowith both of ways it is being used, but I don`t know why.

Add Access Network Permission in AndroidManifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

First add users-permission in AndroidManifest.xml file like this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Second, this pics of code can give you a boolean. Network connection is available or not. so put it in a method and get return of those code like this..
public boolean getCheckedNetStatus(Context context) {
try{
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}catch(Exception e){
Log.e("Net Check Err", e.toString());
return false;
}
}
Have try catch will protect your from unexpected crash your app...
Now Call it to conditionally execute your certain action like this
if(getCheckedNetStatus(yourActivity.this)){
//Net is available
//So do your action
}else{
//Net not available
//you can notify user that net not available
//So you (User) can't do this
}

Related

Realtime Network Check - Android

I have an app and in that, I want to check the real-time network of the mobile phone.
This is my java code:
This is only some of the full java file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
if (checkNetwork() == false) {
Toast noNetwork = Toast.makeText(getApplicationContext(), "Sync is paused, due to no
internet...", Toast.LENGTH_LONG);
noNetwork.show();
} else if (checkNetwork() == true) {
Toast yesNetwork = Toast.makeText(getApplicationContext(), "Sync is turned on...",
Toast.LENGTH_LONG);
yesNetwork.show();
}
// This code we will add later - bottomNavigation.getMenu().removeItem(R.id.navigation_notes);
}
private boolean checkNetwork() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
If I open my app and navigate to this page, it shows the internet is there toast, but at the same time when I turn off mobile data, the other toast which shows internet is not there is not shown. I think the above code is not real-time or there is a problem with the toast, I don't know.
I want to know if there are ways in which I could make the above code real-time. Thanks in advance.
Register a NetworkCallback using registerNetworkCallback() method. Example code is given here.

How to check if I have enabled WIFI before downloading a file? [duplicate]

This question already has answers here:
How do I see if Wi-Fi is connected on Android?
(24 answers)
Closed 3 years ago.
I have a Button that downoad a File, and works fine. If I dont have Internet conection, the file doesnt download (obviously). The problem is that the app continues trying to download, instead of stop it.
I want to show a Toast saying "The device its not connected" or some stuff like that and NOT begin the download process then. I want a function that returns true or false if I have WIFI connection avaiable AT THE MOMENT or not
I try with the answers of these post: How to check currently internet connection is available or not in android , but the function retuns always true, even with Airplane mode.
I download the File with a DownloadManager and continues after download with a BroadcastReceiver.
Add this permission in Manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Following condition will help you
ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()){
// If Wi-Fi connected
}else{
Toast.makeText(getApplicationContext() /*Context field*/,"Please Connect to Wifi",Toast.LENGTH_SHORT).show();
}
Add this permission in Manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use this condition to check if Wifi Connected or not
ConnectivityManager connManager = (ConnectivityManager);getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
Here's Network connectivity checking code
public class NetworUtil {
private static NetworkInfo activeNetwork;
public static boolean isInternetConnected(Context context) {
if (context == null)
return false;
else {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
}
}
Below permission must be required in the AndroidManifest file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to choose the internet connection mode Android

I made an Android application that is used to exchange files with a pc.
The computer and the device are connected to the same network and everything worked very well.
But since I put a 4g sim card, the transfer is no longer done, does anyone know how to solve this problem?
There must be a way to force my application to use only ethernet connection?
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
How I check connection:
public static Boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
boolean isEthernet = false;
if (activeNetwork != null) {
isEthernet = activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET;
}
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting() && isEthernet;
}
Main function:
public void sendFilesInFolder(Boolean bool) {
if (isConnected(MainActivity.this)) {
ProgressBar progressBar;
if (bool) progressBar = mProgressBarD;
else progressBar = mProgressBarM;
fileSender = new FileSender(prefs.getString("ip_adress", null),
Integer.valueOf(prefs.getString("port_dest", null)),
bool, colisageBase, progressBar);
fileSender.execute();
} else {
Toast.makeText(MainActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}

How to use a custom No Internet Connection Available layout when user is offline?

I have been trying to use a custom Image that is to be shown to a user when he is offline and when the user clicks on the image, the activity should be reloaded.
P.s I am using Blogger API
first add this permission to manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
thin in your activty
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
and use like this
if(isNetworkAvailable()){
//internt connect
}else{
// no network
//you can show image here by adding layout and set visibility gone and when no connection set visible
}
You can use Custom Dialog of full Screen to check for internet. So, you can write,
if(isNetworkAvailable()){
//Your Logic for Internet Connection
}else {
val noInternetDialog = Dialog(this, android.R.style.Theme)
noInternetDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
noInternetDialog.setContentView(R.layout.no_internet_layout)
val window = noInternetDialog.window
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
// What ever you have widget, can use them here.
//for example
val button_try_again = noInternetDialog.findViewById(R.id.buttonId)
val image_to_display = noInternetDialog.findViewById(R.id.imageId)
// listeners for image
noInternetDialog.show
}
isNetworkAvaibale() is,
fun isNetworkAvailable(): Boolean {
val connectivityManager = ApplicationInit.getAppContext()
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
PS : Do not forget to add Internet Permissions

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

Categories