samedi 25 juin 2016

How to prevent web view activity from starting when there is no Internet connection?

I have an app with a web view which loads in the second activity. The app has two activities. The second activity starts when a button is pressed in the first activity.

My problem is, I want to prevent the second activity to start and remain on the first activity and show a toast if there is no Internet connection. My network check is done in the second activity.

This is my first activity:

public class FirstActivity extends AppCompatActivity {

    public void startSecondActivity(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

And this is my second activity:

public class SecondActivity extends AppCompatActivity {

    private WebView mWebView;

    public static boolean checkInternetConnection(Context context) {
        ConnectivityManager con_manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        if (!SecondActivity.checkInternetConnection(this)) {
            Toast.makeText(getApplicationContext(), "No Internet Connection!!!", Toast.LENGTH_SHORT).show();
        } else {
            mWebView = (WebView) findViewById(R.id.webView);
            mWebView.setWebViewClient(new CustomWebViewClient());
            mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.loadUrl("http://m.sovran.in/index.php?id=" + token);
        }
    }

Aucun commentaire:

Enregistrer un commentaire