如何在Android 13上后台工作?

问题描述 投票:0回答:1

我构建了每 2 秒通过 HTTP 请求轮询服务器的应用程序, 现在我想让它在屏幕黑时(用户按下锁定屏幕按钮)在后台工作,因为当它**最小化**它的工作。我在三星上测试了该应用程序,我**关闭**该应用程序的电池优化,并通过手机设置将该应用程序添加到“永不休眠的应用程序”列表中,但如果手机处于锁定屏幕状态,我仍然无法进行轮询。

我开发医疗紧急应用程序,我需要一直工作,我尝试添加前台服务,它解决了应用程序在后台(最小化)时的情况,但不是当应用程序处于黑屏锁定屏幕时的情况。

所以我的问题是有什么方法可以每 2 秒轮询一次服务器,即使应用程序在后台(锁定屏幕),我希望应用程序在任何情况下都能继续工作。

android background-process background-service foreground-service android-13
1个回答
0
投票

是的,你可以 使用警报管理器或显示应用程序在后台运行的通知。

服务

// 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();
        }
       
    }

活动

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();
        
              });

不要忘记在清单中

 <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" />
© www.soinside.com 2019 - 2024. All rights reserved.