How to open an Activity when you don’t have internet?

Asked

Viewed 187 times

2

I’m with a project that uses internet, and when there is no internet the same does not leave the menu because I put a lock access to other activit when there is no internet, but in did not open I wanted to play to another specific Action, I can even open a random blank page but the page I request to open does not come, I need help

MENU CODE

public class TRABALHAR extends AppCompatActivity {

private WebView xp4;

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

    if(!isOnline()){
        startActivity(new Intent(TRABALHAR.this,NOTICIAS2.class));
        finish();
    }// verifica conexao com a net


    xp4 = findViewById(R.id.xp4);
    xp4.getSettings().setJavaScriptEnabled(true);
    xp4.setWebViewClient(new WebViewClient());
    xp4.loadUrl("https://clubcooeec1.blogspot.com/p/fazer-parte-da-equipe.html");

}
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnected(); // verifica se tem internet
}

if I take the line

startActivity(new Intent(WORK.this,NOTICIAS2.class));

the application just blocks access to page, but this is not my goal

how I should proceed in this case ?

  • your isOnline method does not check internet connection, just check if the user is with any active internet network(wifi, mobile network...). Now to understand better, when there is no internet, do you want to open another acitivity? By your code is not opening? To me it seems normal.

  • Tried to put the part of this webview into Else??

  • When I run the code without wifi connected the same opens a White screen less the Activity that I want, in Activity that I want will appear that the same is without connection, mass if you have an applicable code that makes actually check the internet and warn the user already help .

  • Hello Renan, I tried to detail the answer well, for me it worked well, and with the Asynctask I put it takes the margin of error for when a user is connected wifi or mobile network, but the internet is oscillating or very low and it is not possible to load the url. Give feedback if it goes right or wrong. Abç

1 answer

1


I made some changes and tested on an API 24, it worked well.

First create an Asynctask extended class, as follows:

public class CarregaPagina extends AsyncTask<String, Void, Boolean> {
    TRABALHAR trabalhar;
    String sUrl;
    int timeout;

    //construtor
    public CarregaPagina(TRABALHAR trabalhar, String sUrl, int timeout) {
        this.trabalhar = trabalhar;
        this.sUrl = sUrl;
        this.timeout = timeout;

    }

    @Override
    protected Boolean doInBackground(String... strings) {
        //se tem algum conexão com a internet
        if (isOnline()) {
            //checa a conexão com a url
            try {

                URL url = new URL(sUrl);
                //abre a conexão
                URLConnection urlConnection = url.openConnection();
                //tempo de resposta
                urlConnection.setConnectTimeout(timeout);
                //conecta
                urlConnection.connect();
                return true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean b) {
        if (b) {
            WebView xp4 = trabalhar.xp4;

            //carrega webview da classe TRABALHAR
            xp4.getSettings().setJavaScriptEnabled(true);
            xp4.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            xp4.getSettings().setLoadWithOverviewMode(true);
            xp4.getSettings().setUseWideViewPort(true);
            xp4.setWebViewClient(new WebViewClient());
            xp4.loadUrl(sUrl);
        } else {
            Toast.makeText(trabalhar, "Erro na conexão", Toast.LENGTH_SHORT).show();
            //Erro na conexão
            chamaActivity();
        }

    }

    private void chamaActivity() {
        Intent i = new Intent(trabalhar, NOTICIAS2.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        trabalhar.startActivity(new Intent(trabalhar, NOTICIAS2.class));
        trabalhar.finish();
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) trabalhar.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnected(); // verifica se tem internet
    }
}

This class will be responsible for checking if the user is connected to the internet and if it is possible to load its url, if it is not able to load the url in the webview, its Acitivty NOTICIAS2 will be called.

Already in your class WORK, just let:

public class TRABALHAR extends AppCompatActivity {
    //deixe público pra poder utilizar na classe CarregaPagina;
    public WebView xp4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trabalhar);
        xp4 = findViewById(R.id.xp4);

        //os parametros na ordem são: contexto, url, e timeout (tempo pra checar a url) em milisegundos.
        CarregaPagina carregaPagina = new CarregaPagina(this, "https://clubcooeec1.blogspot.com/p/fazer-parte-da-equipe.html", 2000);
        //executa a AsyncTask
        carregaPagina.execute();

    }
}
  • Mano so far worked, thanks as soon as release stop giving the prize I send you, only from 7 hours after posting. OK

  • @renansilvadasneves blz brother, but did you understand how it’s working? If you have any questions let me know that I edit the answer and detail more.

  • bro gave error in 2 lines

  • that was these

  • LoadPagina = new Loadthe page(this, "https://clubcooeec1.blogspot.com/p/fazer-part-da-equipe.html", 2000); //executes Asynctask loadPagina.();

  • was on Upload page and chargePagina.execute so red

  • Which error did you get? And which api you’re testing?

  • I’m testing in API 16, maybe that’s it, I didn’t get to execute the code ,but those words are underlined in red, the ones I mentioned above. I’ll print it out.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.