Question

I have an application which works on a user's session which is maintained between the server and the device. I using a ping technique to keep the session alive between the device and server by pinging the server every 1 min if the user is logged in. This is done using a background thread.

  1. Sometimes when I turn OFF the screen and disconnect the device from its power source the background thread gets killed.

  2. Sometimes the thread is active but my WiFi antennae gets turned OFF and my ping fails.

Is my approach correct? Is there a better way of doing this?

My requirement: I need to ping my server every minute to keep the session alive for various reasons and I should do this only if the user is logged in.

Was it helpful?

Solution

You can use this to check your wi-fi connection

private boolean checkInternetConnection()
{
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
    return conMgr.getActiveNetworkInfo().isConnectedOrConnecting();
}

if checkInternetConnection() == false you can turn on wi-fi using this in your manifest

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

and this in your code

WifiManager wifiManager;
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled()){
   wifiManager.setWifiEnabled(false);
}else{
   wifiManager.setWifiEnabled(true);
}

I hope this help you, though this is not an exact answer to your question.

OTHER TIPS

Use Log.d to write messages to the Logcat when an Activity life cycle event occurs, such as onPause, onStop, onDestroy, onCreate, onStart and onResume. Also creating a BroadcastReceiver to log broadcast events is most helpful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top