Friday, July 4, 2014

Programmatically Toggle Background Data

Not the auto sync but the background data altogether.

Optionally you can write your own code to do the same.

Either the same way as the "Settings" app (in ICS/JB) does it:

import android.app.Fragment
import android.content.Context;
import android.net.NetworkPolicyManager;
import android.os.Bundle;

public class MyClass extends Fragment {
    private NetworkPolicyManager mPolicyManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Context context = getActivity();
        mPolicyManager = NetworkPolicyManager.from(context);
    }
   
    private void myFunction(boolean restrictBackground) {
        mPolicyManager.setRestrictBackground(restrictBackground);
    }
}
Or the way the "Secure Settings" plugin does it:

import android.net.IConnectivityManager;
import android.net.IConnectivityManager$Stub;
import android.net.INetworkPolicyManager;
import android.net.INetworkPolicyManager$Stub;
import android.os.IBinder;
import android.os.ServiceManager;

public class MyClass {

    // pre ICS method
    private void myFunction1() {
        IBinder svc = ServiceManager.getService("connectivity");
        IConnectivityManager connectivityManager = IConnectivityManager$Stub.asInterface(svc);
        connectivityManager.setBackgroundDataSetting(false);
    }
   
    // ICS+ method
    private void myFunction2() {
        IBinder svc = ServiceManager.getService("netpolicy");
        INetworkPolicyManager policyManager = INetworkPolicyManager$Stub.asInterface(svc);
        policyManager.setRestrictBackground(false);
    }
}

The latter is just a proof-of-concept, not working code. Since the two methods (myFunction1 and myFunction2) should be applied on an as-needed basis, you should wrap both with the Java Reflection API (ie. use extensive exception handling and call the respective methods dynamically ... and of course handle the case if the methods do not exist on the given Android device). Both approaches use undocumented functions (ie. not described in the official API documentation at https://developer.android.com/reference/ ), so your implementation might break in any future Android versions (but again ... using only public API functions does not guarantee backwards compatibility either ... they can and do change all the time :-) ).

source: https://groups.google.com/forum/#!msg/tasker/vBUNvqNhJeM/fxjq3VZraeAJ

No comments:

Post a Comment