Skip to content Skip to sidebar Skip to footer

Slower Android When Not Connected To Charger?

I'm trying to develop simple android application which monitors specified url using http client and once defined condition is met it should perform notification actions. I have on

Solution 1:

The matter probably is that phone goes to sleep mode when it stops almost all activity and slows down CPU. It is used to save battery. Timers on Handler.postDelayed() for example won't work properly (not called on time). There's special concept for this matter - for activities that needs to be performed in sleep mode, you need to use AlarmManager, see Scheduling Repeating Alarms

The matter is that your app needs to register with AlarmManager, and then it will receive scheduled events when phone wakes up from sleep mode. Your app needs to get lock with PowerManager to perform activities (in your case it's downloading JSON from network), which you do not want to be interrupted with sleep mode while you're executing them. Consider this example:

publicclassAlarmManagerBroadcastReceiverextendsBroadcastReceiver {

    /**
     * This method is called when we are waking up by AlarmManager
     */@OverridepublicvoidonReceive(Context context, Intent intent) {
        PowerManagerpm= (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLockwl= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pulse app");
        //Acquire the lock
        wl.acquire();

        //You can do the processing here.//Release the lock
        wl.release();
    }

    /**
     * Register our app with AlarmManager to start receiving intents from AlarmManager
     */publicstaticvoidsetAlarm(Context context)
    {
        intinterval=10; // delay in secs
        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intentintent=newIntent(context, AlarmManagerBroadcastReceiver.class);
        PendingIntentpi= PendingIntent.getBroadcast(context, 0, intent, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval*1000 , pi);
    }

    /**
     * Unregister the app with AlarmManager, call this to stop receiving intents from AlarmManager
     */publicstaticvoidcancelAlarm(Context context)
    {
        Intentintent=newIntent(context, AlarmManagerBroadcastReceiver.class);
        PendingIntentsender= PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManageralarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }

}

This code needs android.permission.WAKE_LOCK permission in Manifest file.

Another post about AlarmManager usage: Android: How to use AlarmManager

And this: prevent mobile from going into sleep mode when app is running

Article at the first link says that it's preferable to use Sync Adapters for such purpose, but I haven't used them myself.

Post a Comment for "Slower Android When Not Connected To Charger?"