How to make android.app.Service so that even when the phone screen is off, it works? Here is its source code:

 public class S extends Service { @Override public void onStart(Intent i1, int i2) { new Timer().schedule(new TimerTask() { @Override public void run() { //..........// return; } }, 60000, 60000); } @Override public IBinder onBind(Intent i1) { return null; } } 

I run it like this:

 public class Main extends AppCompatActivity { Intent i1; @Override protected void onCreate(Bundle i1) { super.onCreate(i1); setContentView(R.layout.layout_main); this.i1 = new Intent(this, S.class); startService(this.i1); return; } @Override protected void onDestroy() { stopService(this.i1); super.onDestroy(); return; } } 

The theory says: "Unlike Activity, services in Android work as background processes ... A service can continue to work until someone stops it or it stops itself." But as soon as I turn off the phone screen, the service stops working. She resumes her work only after I unlock the phone. How to fix this error?

    2 answers 2

    This is not a mistake, it should be so that the phone goes to sleep and does not survive the battery. Given the presence of a timer, can it be better to use the AlarmManager ?

    If you really need to in this form, add the permission to android.permission.WAKE_LOCK and prohibit you to fall asleep:

     PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG"); wakeLock.acquire(); // нужный код wakeLock.release(); 
    • And if you want the phone to fall asleep and the screen was off? - nick
    • @Lesperanza and how do you imagine that the processor "slept", but at the same time was engaged in the execution of the code of your service? About VK in the explanation - read about Google Cloud Messaging: developers.google.com/cloud-messaging - VAndrJ
    • Already solved the question. I do not know how it can be, therefore I asked. I tried various solutions and found the right one. You can see my answer. I did not say how I should start the Service - from under BroadcastReceiver, Activity, etc. It doesn't matter to me. - nick

    In order for the Service work regardless of the screen, it is necessary to launch it not from under the Activity , but, for example, from the BroadcastReceiver . At least my problem was this.