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?
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.”
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With