android – Application work when the screen is off

Question:

I would like to know what to use in order for the application to work in "sleep" mode (when you press the shutdown button)? Tried using the Service class, but when the screen is turned off, it "stalls". I know I am missing some important part (in terms of access permissions or something similar), but I myself could not find it. The actual code:

public class MyService extends Service {

final String LOG_TAG = "myLogs";

@Override
public IBinder onBind(Intent intent) {

    return null;
}

public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "onCreate");
}


public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");
    someTask();
    return super.onStartCommand(intent, flags, startId);
}

public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "onDestroy");
}

public void someTask() {
   ......
}
}

In Main, I call the service when the application is opened:

public class MainActivity extends AppCompatActivity {
final String LOG_TAG = "myLogs";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startService(new Intent(this, MyService.class));
}

Answer:

And it is right. So it is conceived so that when the screen is locked, the battery of the device is not discharged.

If, nevertheless, you want, then use WakeLock and PowerManager :

PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyWakeLock"); 
wakeLock.acquire();
Scroll to Top