Search code examples
androidhttpwebrequestconnectionsleepwakelock

Android internet connection problem on sleep mode?


I have a service Activity and a thread in it. Problem is when phone go to sleep mode, thread doesnt send http request And i check the network state if it is not connect i work to connect it but i get "Permission denial: writing to secure settings requires android.permission.WRITE_SECURE_SETTINGS" error. But i already put the permission tag in AndroidManifest.xml. I also try this:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK , "TAG");
wl.acquire();

But it is not solve my problem. phone Already go to sleep mode. Here is my checkNetwork code:

private boolean checkNetwork(){
    try{
        Context context = getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if(info == null){
            connectivity.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
            int status = connectivity.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "cmwap");
            NetworkInfo info1 = connectivity.getActiveNetworkInfo();
            return false;
        }
        if (info.getState() == NetworkInfo.State.CONNECTED )
            return true;
        return false;

    }catch(Exception ex){
        return false;
    }
}

public class MainActivity extends Service { .....

private Runnable httpThread = new Runnable() {

        public void run() {
//i send http request here
}
}

Please help..


Solution

  • Even though your application requested android.permission.WRITE_SECURE_SETTINGS in AndroidManifest.xml, it does not mean this permission will be granted to your application in runtime.

    In fact, for this particular permission (android.permission.WRITE_SECURE_SETTINGS) to be granted, your application must be signed with System certificate. And only vendor of the device can usually do that (for production devices).