java - Internet listener Android example -
i working on android app continuously remains connected internet. if internet down should give appropriate message user.
is there thing internet listener? or how implement event when ever internet connection not available should give alert.
create 1 broadcast receiver , register in manifest file.
first create new class networkstatereceiver
, extend broadcastreceiver.
public class networkstatereceiver extends broadcastreceiver { public void onreceive(context context, intent intent) { log.d("app","network connectivity change"); if(intent.getextras()!=null) { networkinfo ni=(networkinfo) intent.getextras().get(connectivitymanager.extra_network_info); if(ni!=null && ni.getstate()==networkinfo.state.connected) { log.i("app","network "+ni.gettypename()+" connected"); } } if(intent.getextras().getboolean(connectivitymanager.extra_no_connectivity,boolean.false)) { log.d("app","there's no network connectivity"); } } }
put code in androidmanifest.xml under "application" element:
<receiver android:name=".networkstatereceiver"> <intent-filter> <action android:name="android.net.conn.connectivity_change" /> </intent-filter> </receiver>
and add permission
<uses-permission android:name="android.permission.access_network_state"/>
edit
this code detects connectivity change cannot tell whether network connected has internet access. use method check -
public static boolean hasactiveinternetconnection(context context) { if (isnetworkavailable(context)) { try { httpurlconnection urlc = (httpurlconnection) (new url("http://www.google.com").openconnection()); urlc.setrequestproperty("user-agent", "test"); urlc.setrequestproperty("connection", "close"); urlc.setconnecttimeout(1500); urlc.connect(); return (urlc.getresponsecode() == 200); } catch (ioexception e) { log.e(log_tag, "error checking internet connection", e); } } else { log.d(log_tag, "no network available!"); } return false; }
Comments
Post a Comment