Question

I've written a BackupAgent to backup my data, but I want to enable the backup only when WiFi is connected and not GPRS/3G/4G. Can I control that programmatically ?

Was it helpful?

Solution

Wifi State can always be known as follows :

1) Get a WifiManager object using the method Context.getSystemService(Context.WIFI_SERVICE)

2) Use the isWifiEnabled class to know the state of Wifi.

To know the status of Data Connectivity of Cellphone, get an Instance using
TelephonyManager tm = Context.getSystemService(Context.TELEPHONY_SERVICE), and then use

tm.getDataState to know the status of data connectivity.

Now, run your BackupAgent when the return value of getDataState is TelephonyManager.DATA_DISCONNECTED and the return value of isWifiEnabled is true.

To be able to disable the backup once the connection (3G/WiFi) is dropped , create a new method is follows :

enter code here  
protected void checkMyConnectivity()


{

if (tm.getDataState ==  TelephonyManager.DATA_DISCONNECTED && wm.isWifiEnabled==true)

return true;

else

return false;

}`

And use this code whenever you want to check the connectivity and if the return value is false, stop the upload. If you want to be very specific, use a while loop instead.

OTHER TIPS

1) whenever you dont have wifi that is use the Wifi service and if no wifi then un-sunc the account from the phone settings programatically

AccountManager accountManager = AccountManager.get(this); Account[] accounts = accountManager.getAccounts(); Log.i(TAG,"Accounts size "+accounts.length);for(Account acc:accounts){ Log.d(TAG,"acc name "+acc.name+" acc type "+acc.type); boolean isSync = ContentResolver.isSyncActive(acc, ContactsContract.Settings.CONTENT_URI.toString()); Log.d(enter code here`TAG,"isSync "+isSync); cr.setSyncAutomatically(acc, , false);// here you are unsyncing the mail account }

protected boolean isWifiConnectivity() {
    TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
    WifiManager wifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
    return (telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED && wifiManager.isWifiEnabled());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top