I have very little experience with android development, i have made a simple app with a webview, i want to be able to alert the user when there is no network connectivity. however i am not able to get the alert dialog to show up. The code compiles fine without any errors or warnings.
MainActivity.java
package dk.zerone.vuc;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
public final boolean networkCheck() {
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
return true;
} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {
return false;
}
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(networkCheck()) {
// INTERNET IS AVAILABLE, DO STUFF..
} else {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Reset...");
alertDialog.setMessage("R u sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
} });
alertDialog.show();
}
/* Splash screen */
// ...
/* WebView */
WebView webview = new WebView(this);
webview.setWebViewClient(new WebViewClient());
setContentView(webview);
Uri uri = Uri.parse("http://mobil.vucfyn.dk/mobil");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I am testing the code in the emulator, disabling the network with F8 or Airplane mode does not trigger the dialog or network check.
What am i doing wrong?
Kind regards
For one thing you are not showing your activity to the user in each case.You are launching Browser in oncreate.
You are not using WebView to load the url, you are using the preloaded Browser to show your URL. Use
instead of last 3 lines in your oncreate function