Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconnect to the internet automatically

Tags:

android

I'm developing an Android chat application. On startup the application launches a service. The service connects to the chat server. If for some reason the connection goes down, the user can click a button and the reconnect() function gets called.

The application runs on a mobile device. The application connects to the Internet via Wi-Fi. If the user, walking with his phone, goes out of the Wi-Fi coverage area, the connection goes down. I want my application to automatically try to reconnect to the Internet in such cases. What's the best way to do this in your opinion?

like image 853
mneri Avatar asked Mar 05 '12 11:03

mneri


People also ask

How do I automatically Connect to Internet Windows 10?

Make your way to your “Start” button and restart your computer. Once your computer has rebooted, navigate back to the Wi-Fi icon on your taskbar and click it. Choose your Wi-Fi network from the pop-up menu and check the box next to where it says, “Connect Automatically.” Now click “Connect.”

Why is my Wi-Fi not automatically connecting?

The Cause. A wide variety of factors causes Wi-Fi connection problems. Some are simple and easy to fix, like being too far from the router, having Airplane mode turned on, or having a weak signal. However, the issue can be caused by something else like a software bug or problems with the router or modem.


1 Answers

Add to Manifest:

...
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
<uses-permission android:name="android.permission.INTERNET">            </uses-permission>
...
    <receiver android:name=".Internet" android:enabled="true"> 
        <intent-filter> 
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter> 
    </receiver> 
...

Receiver:

    package YourPackage;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;

    public class Internet extends BroadcastReceiver
    {    
        @Override
        public void onReceive(final Context context, Intent intent) 
        {   
            if (intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE"))
            {
                if isInternet(context)
                { 
                    // Your Code
                }
            }       
        }

        public boolean isInternet(Context context) 
        {
            ConnectivityManager IM = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = IM.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }     
    }
like image 98
XXX Avatar answered Oct 16 '22 05:10

XXX