0

I built app that do polling to the server via HTTP requests every 2 seconds, and now I want to make it work even in the background when the screen is black (user press on lock screen button) because when its **minimized **its work. I testing the app on Samsung and I **TURNOFF **the battery optimization for the app and added the app to "never sleeping apps" list via phone settings, and still I not able to make the polling if the phone in lock screen.

I develop medical emergency app and I need to work always, I tried to add FOREGROUND SERVICE its solve the case when the app in the background(minimized) but not when the app in lock screen with black screen.

So my question is there any way to make polling to the server every 2 seconds even if the app in the background(lock screen), I want that the app will continue to work in any case.

Eli
  • 31
  • 5

1 Answers1

0

yes u can Use alarm manager or show notifications that the app is running in the background.

Service

// LifecycleService with MutableLiveData If you want to use mvvm
 //You can exchange it for the service

    public class AlarmService extends LifecycleService {
       
        public static MutableLiveData<String> status =new MutableLiveData<>();
        private Notification.Builder builder;
        private NotificationChannel notificationChannel;
 
    
       
        @Override
        public void onCreate() {
            super.onCreate();
    
            
    
            notificationChannel=new NotificationChannel("channel","channel", NotificationManager.IMPORTANCE_HIGH);
    
           
            startForeground(500,notification());
    
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
    
           
    
             Handler handler = new Handler();
             Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.d("TAG", "run: ");
                        // your Code
                     status.postValue("run");//change status If you want to send data to an activity
                    handler.postDelayed(this, 1000);//change this 1000ms
                }
            };
            handler.postDelayed(runnable, 1000) //change this 1000ms;
            return START_STICKY;
        }
    
    
       
    
    
      
        public Notification notification(){
            Intent intent=new Intent(this,getClass());
            @SuppressLint("UnspecifiedImmutableFlag")
            PendingIntent pendingIntent= PendingIntent.getService(this,1,intent,PendingIntent.FLAG_CANCEL_CURRENT);
    
            builder =new Notification.Builder(this,"channel");
            builder.setContentText("The service runs in the forground");
            builder.setContentTitle("Service is running");
            builder.setSmallIcon(R.drawable.ic_send);
    
    
            NotificationManager notificationManager= (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
            return builder.build();
        }
       
    }

Actvity

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            Intent intent = new Intent();
            String packageName =getPackageName();
            PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);

            }

}
    

     Intent intent =new Intent(getApplicationContext(),AlarmService.class);
                           startService(intent);
    
        AlarmService.status.observe(this, s -> {
     Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
        
              });

Don't forget in manifest

 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />


     <service
                android:name=".AlarmService"
                android:enabled="true"
                android:label="Alarm"
                android:stopWithTask="false" />