首页 > 解决方案 > 手机空闲/打瞌睡/锁定时Android服务不工作

问题描述

晚上好,

几天来我一直在努力实现一些目标,我真的不知道还能尝试什么,我基本上已经尝试了我在网上找到的所有东西,但它仍然不起作用,但我有一种感觉,一旦我找到了解决方案它必须非常简单。

我正在做一个更大的项目,但在这里我只是想得到一个非常简单的例子来工作,我以后可以适应我的项目。

我想做的事

我想让一个计数器在 1200 秒(20 分钟)内每秒添加 +1,并在每次计数时写入文件。我最终应该得到一个包含 1200 行的文件,每个样本都有一个时间戳。

我是如何做到的

我已经尝试了一百万件事,但在这里,我只是回到了一个非常基本的例子,所以我可以展示它并寻求帮助:

我的问题

虽然手机屏幕处于打开状态,但一切正常,但一旦我锁定屏幕并将手机放入口袋,取决于我正在测试的手机,它开始出现故障。

我想要什么

如果有人能告诉我要修改/添加/更改什么,甚至为我做,然后在这里写回(这是一个非常简单的项目),我将非常感激,我浪费了大量时间,我只是无法按右键。

代码

由于这是一个非常简单的项目,我将在这里复制它包含的 4 个部分:

XML activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/start_button"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_marginStart="52dp"
        android:layout_marginBottom="116dp"
        android:onClick="startProcess"
        android:text="@string/button_label_start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/counter_textView"
        android:layout_width="383dp"
        android:layout_height="412dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/counter_label_value"
        android:textSize="160sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.428"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.169" />

</androidx.constraintlayout.widget.ConstraintLayout>

清单AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name=".ForegroundService"
            android:enabled="true"
            android:exported="true"
            android:process=":externalProcess">
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

主要MainActivity.java

package com.example.helloworld;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public static final String CHANNEL_ID = "ForegroundServiceChannel";
    private TextView mShowCount;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        int mCount = data.getIntExtra(ForegroundService.FOREGROUND_MESSAGE, -1);
        if(mShowCount != null)
            mShowCount.setText(Integer.toString(mCount));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mShowCount = findViewById(R.id.counter_textView);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    public void startProcess(View view) {
        PendingIntent pendingResult = createPendingResult(100, new Intent(), 0);
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        serviceIntent.putExtra("pendingIntent", pendingResult);
        ContextCompat.startForegroundService(this, serviceIntent);
    }

    public void stopProcess(View view) {
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        stopService(serviceIntent);
    }
}

前台服务ForegroundService.java

package com.example.helloworld;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import androidx.core.app.NotificationCompat;

import java.io.File;
import java.io.FileWriter;
import java.util.Date;

public class ForegroundService extends Service {

    public static final String CHANNEL_ID = "ForegroundServiceChannel";
    public static final String FOREGROUND_MESSAGE = "com.example.helloworld.FOREGROUND_MESSAGE";

    private PendingIntent data;
    private int mCount;
    private File basePath;

    public ForegroundService() {
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

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

    @Override
    public boolean stopService(Intent name) {
        return super.stopService(name);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");

        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);
        Notification notification = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);
        data = intent.getParcelableExtra("pendingIntent");
        this.basePath = this.getExternalFilesDir("recs");

        mCount = 0;
        new Thread(new Runnable() {
            public void run() {
                try {
                    while(mCount < 1200) {
                        Intent resultIntent = new Intent();
                        resultIntent.putExtra(FOREGROUND_MESSAGE, ++mCount);
                        writeFile((new Date().getTime() / 1000) + " Increasing counter: " + mCount + "\n");
                        data.send(ForegroundService.this, 200, resultIntent);
                        SystemClock.sleep(1000);
                    }
                }catch (Exception ignored){}
            }
        }).start();

        //stopSelf();
        return START_NOT_STICKY;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

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

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

    private void writeFile(String data)
    {
        File file = new File (basePath,"test");
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                Log.e("RECORDING", "Error creating SAVE BASE PATH");
            }
        }

        try{
            File counter_file = new File(file, "counter.txt");
            FileWriter writer = new FileWriter(counter_file, true);
            writer.append(data);
            writer.flush();
            writer.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

我知道我的要求可能有点过分,但此时我非常绝望。如果有人能提出一个可行的解决方案,我会非常感激。

非常感谢。

标签: androidbackground-processforeground-serviceandroid-doze-and-standbyidle-processing

解决方案


您应该尝试使用WakeLock来自官方的android文档

这将防止在完成特定任务之前让 CPU 进入睡眠状态。

在您的服务的 onCreate() 方法中

@Override
public void onCreate() {
    super.onCreate();
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "MyApp::MyWakelockTag");
    wakeLock.acquire();
    /*Rest of the
      code goes here*/
}

当你的目的结束时不要忘记释放你的唤醒锁,否则你可能会很快耗尽你的用户电池。

@Override
public void onDestroy()
 {
   super.onDestroy();
   wakeLock.release();
 }

推荐阅读