java - Android: Activity establish network connection -
i have activity looks data web in oncreate method. activity activated user hitting notification. common problem user turn on phone, unlock it, slide open notifications, tap notification, , activity activate before phone done connecting internet.
i have friendly alertdialog pops informing user data couldn't received , try again when network connected; is there way activity actively tell phone connect , detect connection being made , wait connection establish, , load data successfully?
usually, this:
@override public void onresume(){ super.onresume(); // first, check connectivity if ( isonline ){ // things if there's network connection }else{ // seems there's no internet connection // ask user activate new alertdialog.builder(youractivity.this) .settitle("connection failed") .setmessage("this application requires network access. please, enable " + "mobile network or wi-fi.") .setpositivebutton("accept", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // doing, jul youractivity.this.startactivity(new intent(settings.action_wireless_settings)); } }) .setnegativebutton("cancel", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { youractivity.this.finish(); } }) .show(); } }
the idea ask user go , configure network connection. then, if user want configure it, call settings.action_wireless_settings
intent.
also, notice isonline
variable, boolean tells whether there's network connection or not. in order set variable can use external simple class this:
public class checkconnectivity { public static boolean isonline(context context) { connectivitymanager cm = (connectivitymanager) context.getsystemservice(context.connectivity_service); if( cm == null ) return false; networkinfo info = cm.getactivenetworkinfo(); if( info == null ) return false; return info.isconnectedorconnecting(); } }
also, have add permission androidmanifest.xml
file:
<uses-permission android:name="android.permission.access_network_state" />
Comments
Post a Comment