2

My app needs internet connection so it check if user have connection or not. But it check that only when activity starts so how I can detect if user has no connection after activity is started?

HERE IS CODE WHAT I USE TO DETECT CONNECTION WHEN ACTIVITY STARTS:

@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main );

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            if (!info.isConnected()) {
            }
        }
        else {
            Intent intent = new Intent(hello.this, connectionerror.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            hello.this.finish();
        }

..... my apps other code continues here........

Eljas
  • 1,187
  • 4
  • 17
  • 37
  • 1
    Have you tried placing the connectivity code inside a method? That way you can call it whenever you want without code reuse. – Matt K Aug 08 '11 at 21:27

1 Answers1

3

You can register a BroadcastReceiver for android.net.conn.CONNECTIVITY_CHANGE. You can either look in the intent (for what network changed), or just re-check with the ConnectivityManager.

Erich Douglass
  • 51,744
  • 11
  • 75
  • 60
  • Not very good question, but nice answer. The CONNECTIVITY_CHANGE broadcast sounds very useful. Thanks – peter.bartos Aug 08 '11 at 21:25
  • @Erich Douglass How do I do that? – Eljas Aug 10 '11 at 19:44
  • Maybe it is a very late answer, but if anyone wants to use a broadcast receiver for checking the connectivity, this might be a helpful link: http://android-er.blogspot.com/2011/01/monitor-wifi-status-and-information.html – b.i Apr 17 '12 at 06:22