0

I want to check the internet connection constantly and close the app with a warning message if connection is lost. How can i manage to do that?

platypus
  • 706
  • 2
  • 18
  • 40

2 Answers2

1

Check Internet Connectivity via Phone Background service (such as AlermManager Service) then close the app if no connection found.

thanks.

Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
1
close the app

Don't try to kill the process and its not recommended way of closing application. Either call finish() on all activities or call moveTaskToBack(true).

For Solution Here you go.

You will need to register for and handle BroadCastReceiver android.net.conn.CONNECTIVITY_CHANGE

Step 1

Include following permission in manifest

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

Step2

Let Android know which class will be register for BroadCast Receiver.

<receiver android:name="ConnectivityReceiver_package_name.ConnectivityReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

Step 3

Put your logic for various Network States.

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

     String action = intent.getAction();

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);

     if(noConnectivity){

         //Show Warning Message
         //Close Application the way i suggested
     }

    }

}
Vipul
  • 27,808
  • 7
  • 60
  • 75
  • I tried it but doesnt work when i close or open the internet connection. Shall i do something with "action" variable too? It seems to be unused. – platypus Jun 10 '12 at 17:01
  • put some logs in if(noConnectivity) {} block and check if control reached in block if you disconnect the internet. – Vipul Jun 10 '12 at 17:04
  • Should i put ConnectivityReceiver in other classes as an inner class or something like that? Because I followed all the steps but it didn't work for me. – platypus Jun 10 '12 at 17:26
  • ohh i got some error in code i posted above... should be changed to – Vipul Jun 10 '12 at 17:52