If your android app is dependent on internet then you need to check whether your device is having internet connection or not at the starting of your app, so to check the same copy the code below :-
To know the Network state in your app you need to add the permission in your manifest file
"<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />".
Here I have created the method DetectNetwork which returns the boolean value , that will be true if the internet connection is available and false if not.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
private boolean mnetwork;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mnetwork=DetectNetwork();
if(mnetwork)
{
Toast.makeText(this,"Network is "+mnetwork,Toast.LENGTH_LONG).show();
// Do something
}
}
private boolean DetectNetwork() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
0 Comment(s)