简体   繁体   中英

Take user to settings if there's no internet connection

As a newbie in java I am unable to link these two code snippets:

If there is no internet connection:

     public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }

Then, popup a dialog box with a notice and settings/cancel buttons.

      public void showNoConnectionDialog(Context ctx1) {
      final Context ctx = ctx1;
      AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
      builder.setCancelable(true);
      builder.setMessage(R.string.no_connection);
      builder.setTitle(R.string.no_connection_title);
      builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
              ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
          }
      });
      builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
              return;
          }
      });
      builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
          public void onCancel(DialogInterface dialog) {
              return;
          }
      });

      builder.show();
  }

Can anyone give some direction.

Use like this.

if(!isOnline()) {
   showNoConnectionDialog(MainActivity.this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM