Question

i am looking for method which will check data connection is enable or disable . if data enable then open a link in webView else toast (Data is disable).

Below my code which handle webview

public class Question_web extends Activity { /** Called when the activity is first created. */

WebView webview;
ProgressBar progressBar;
int a;
String value;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.webcontent);

    value = getIntent().getExtras().getString("url");


    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    WebView engine = (WebView) findViewById(R.id.webviews);




    engine.setDownloadListener(new DownloadListener() {
          public void onDownloadStart(String url, String userAgent,
                  String contentDisposition, String mimetype,
                  long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            Toast.makeText(getBaseContext(), "downloading", Toast.LENGTH_SHORT).show();
            i.setData(Uri.parse(url));
            startActivity(i);
          }
      });


    engine.setWebViewClient(new FixedWebViewClient() {
        public void onPageStarted(WebView view, String url, Bitmap favicon)
        {
            progressBar.setVisibility(View.VISIBLE);
        }

        public void onPageFinished(WebView view, String url)
        {
            progressBar.setVisibility(View.GONE);
        }
    });
    engine.getSettings().setJavaScriptEnabled(true);

    engine.loadUrl(value);
}

public void onBackPressed() {
    WebView engine = (WebView) findViewById(R.id.webviews);
    String url = engine.getUrl(); 
    if (url.equals(value) ||
        url.equals(value)) {
        // exit
        super.onBackPressed();
    } else {
        // go back a page, like normal browser
        engine.goBack();
    }
}

private class FixedWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

}

Was it helpful?

Solution

We can check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() of NetworkInfo class.

This is example is available on Android doc,

ConnectivityManager connMgr = (ConnectivityManager) 
    getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
    // fetch data
} else {
    // display error
}

See here and here for details.

Remember to add permissions in manifest. Follow this step by step tutorial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top