Detecting Internet Connection and Show an Alert Dialog in Android
Step-1:Create a class like ConnectionDetector.java
package bd.base.mamun.tabsswipe;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Step-2 :
public class ComingSoonActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coming_soon);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle(Html.fromHtml("<font color='#7F02AE'> <b>Star Cineplex</b></font>"));
builder.setMessage(Html.fromHtml("<font color='#120049'>Your data services are not working.Please check your data services.</font>"));
builder.setPositiveButton(Html.fromHtml("<font color='#7F02AE'><b>OK</b></font>"), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent);
finish();
}
});
/* builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});*/
AlertDialog alert=builder.create();
alert.show();
}
}
To Get:
No comments:
Post a Comment