首页 > 解决方案 > 即使获得“PARTIAL_WAKE_LOCK”,前台服务也会因打盹模式而停止

问题描述

正如我的标题所说,我有一个FOREGROUNDSERVICE在大约 3 分钟后停止(我猜是打瞌睡模式),并停止获取 Accelerometry。我确实使用 aPARTIAL_WAKE_LOCK并返回START_STICKY...但我不明白为什么会发生这种情况。我确实需要 Acc 不停止记录并将值记录在文件中……停止采集的方法是电池检查、可用空间检查或单击应用程序的按钮。

我在 Android 6.0.1 (API 23) 上测试了以下应用程序的实现,并且工作起来很迷人。在小米 Pocophone Android 10 设备(API 29)上测试相同的应用程序时,3 分钟后打盹模式(我猜)启动并停止 acc 采集......

关于为什么的任何想法?从理论上讲,前台服务应该保持 CPU 运行,并且通过部分唤醒锁,我应该确保它继续运行并获取 ACC ......

这是我的服务:

public class AccelerometryService extends Service implements SensorEventListener {
    // WakeLock variable to keep CPU running obtaining Acc
    private PowerManager.WakeLock wakeLock;

    //Notification Variable to show that Acc has started
    private NotificationChannel notChannel = null;
    private NotificationManager nMservice = null;
    Intent notifIntent = null;
    PendingIntent pendingIntent = null;
    private int NOTIFICATION = 112020592;
    private String channelID = "AccRecordService";

    //Accelerometry variables
    private SensorManager sensorManager = null;
    private Sensor sensor = null;

    //File Writting
    private long SystemTime = 0;
    private File rawDataFolder = null;
    private String FileName = null;
    private File rawDataTxt = null;
    private FileOutputStream fileOutputStream = null;

    //Acc data sharing
    private Observable oString = null;
    public static final String ACCNOTIFICATION = "com.example.android.sleeppos";




    @SuppressLint("WakelockTimeout")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Toast.makeText(this, "Logging service started new", Toast.LENGTH_SHORT).show();

        //Acquire wake lock
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WLTAG:MyWakelockTag");
        wakeLock.acquire();


        //Display notification
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(this.channelID, "AccBackgroundService");
        }
        this.notifIntent = new Intent(this, MainActivity.class);
        this.pendingIntent = PendingIntent.getActivity(this, 0, this.notifIntent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder =  new Notification.Builder(this, this.channelID)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle("SleepPos app")
                    .setContentText("Acc has started being recorded")
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setContentIntent(this.pendingIntent)
                    .setOngoing(true);
            startForeground(this.NOTIFICATION, builder.build());
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, this.channelID)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle("SleepPos app")
                    .setContentText("Acc has started being recorded")
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setContentIntent(this.pendingIntent)
                    .setOngoing(true);
            startForeground(this.NOTIFICATION, builder.build());
        }


        // register Acc listener
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);


        //Parse variables given from the intent
        this.rawDataFolder = (File) intent.getExtras().get("DataFolder");
        this.FileName = intent.getStringExtra("FileName");
        this.SystemTime = intent.getLongExtra("SystemTime", 0);
        this.rawDataTxt = new File(this.rawDataFolder, this.FileName);
        try {
            this.rawDataTxt.createNewFile();
            this.fileOutputStream = new FileOutputStream(this.rawDataTxt);
            this.fileOutputStream.write(("Time_elapsed_(nanoseconds);X-Axis;Y-Axis;Z-Axis" + System.lineSeparator()).getBytes());
        } catch (IOException ioe) {
            Log.v("ErrorFile", "Error while creating empty file:");
        }

        return START_STICKY;
    }

       @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //unregister sensor listener
        sensorManager.unregisterListener(this);

        //cancel notification
        stopForeground(true);

        //Close the file being used to register Acc
        try {
            this.fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //release wakeLock
        wakeLock.release();

        Log.v("DEBUG_SLEEPPOS","onDestroyDone");
        //Stop Service
        stopSelf();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // grab the values and timestamp -- off the main thread
        long dataTime = event.timestamp;

        // Call the file handle to write
        try {
            String delimiter = ";";
            fileOutputStream.write(((dataTime - AccelerometryService.this.SystemTime) + delimiter +
                    event.values[0] + delimiter +
                    event.values[1] + delimiter +
                    event.values[2] +
                    System.lineSeparator()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }



    @RequiresApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName) {
        this.notChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        this.notChannel.enableLights(true);
        this.notChannel.setLightColor(Color.RED);
        this.notChannel.enableVibration(true);
        long[] Vibrations = {100, 200, 300, 400, 500, 400, 300, 200, 400};
        this.notChannel.setVibrationPattern(Vibrations);
        this.notChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        this.notChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
        this.nMservice = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        this.nMservice.createNotificationChannel(this.notChannel);
    }


}

更新:adb shell dumpsys deviceidle force-idle在终端上测试了强制空闲状态的命令,但 Acc 仍在获取......所以不知道为什么它在我的 XIAOMI Pocophone F1 Android 10(API 29)上 3 分钟后停止。我不知道是否可以使用任何其他命令强制打盹模式...

标签: javaandroidandroid-servicewakelockforeground-service

解决方案


推荐阅读