3

I need to detect whether the Android device is connected or disconnected to the internet on splash... if there's no connection, the application won't open.. i have try many time.. but i failed.. this is my splash's source code :

private Handler splashHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Runnable r = new Runnable(){
        public void run(){
            Intent brain = new Intent(Splash.this, MainMenu.class);
            startActivity(brain);
            finish();
        }
    };
    setContentView(R.layout.splashscreen);
    splashHandler.postDelayed(r, 2000);
}

public void onResume(Bundle savedInstanceState){
    super.onResume();
}

}

if there's someone help me and give me a source code.. tell me where i must put it..

Menma
  • 799
  • 1
  • 9
  • 35

2 Answers2

3

From this SO Post: Detect whether there is an Internet connection available on Android

Here is what your code should look like:

private Handler splashHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Runnable r = new Runnable(){
        public void run(){
            Intent brain = new Intent(Splash.this, MainMenu.class);
            startActivity(brain);
            finish();
        }
    };
    setContentView(R.layout.splashscreen);
    if(isNetworkAvailable())
        splashHandler.postDelayed(r, 2000);
    else {
        //Notify user they aren't connected
        Toast.makeText(getApplicationContext(), "You aren't connected to the internet.", Toast.LENGTH_SHORT).show();
        //close the app
        finish();
    }
}

public void onResume(Bundle savedInstanceState){
    super.onResume();
}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

As stated in the link above, you'll also need to add:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

to your AndroidManifest.xml file...

Community
  • 1
  • 1
Salil Pandit
  • 1,498
  • 10
  • 13
0

Take a look at this. It's a BroadcastReciver with action ConnectivityManager.CONNECTIVITY_ACTION. and it allows to the system whenever a change in the network connectivity occurs.

I hope it helps.

yugidroid
  • 6,640
  • 2
  • 30
  • 45