This post is to "Detecting internet connection status in your app" its very easy to do , below is the code how to do this:-
1. Open your manifests file and take following permission :-
3. Now call this method in onCreate of class like following :-
For testing i am printing the log you can also keep toast messages here
1. Open your manifests file and take following permission :-
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>2. Open your class where you wants to check the internet connection and write one method like following this method will return true or false :-
private boolean amIConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
3. Now call this method in onCreate of class like following :-
if(amIConnected()) { Log.d("supriya","..user is connected"+amIConnected()); } else { Log.d("supriya","not connected"); }4. Full code like following :-
public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(amIConnected()) { Log.d("supriya","..user is connected"+amIConnected()); } else { Log.d("supriya","not connected"); } } private boolean amIConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }Note:-
For testing i am printing the log you can also keep toast messages here
No comments:
Post a Comment