设备进入睡眠模式后,为什么前台服务会停止工作

时间:2019-05-14 07:19:07

标签: java android foreground-service

我想创建一个不断检查位置变化的应用,并将当前位置放到火力中(例如,跑步者应用)。

不幸的是,每次设备进入睡眠模式时,前台服务都将停止或暂停。

对于初学者,我想创建一个前台服务,该服务每秒不断地将信息写入基础(可能是时间戳或简单字符串)。 一段时间后,它只是停止写入firebase而无需调用stopself()。

该服务在仿真器上可以正常工作(即使已进入睡眠状态),但在实际设备上进行测试时会停止运行–在我的情况下为华为Android 8.1.0。 我该怎么办才能迫使服务在设备的每种状态下运行?

My MainActivity: 

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
             Intent intent = new Intent(this, MyService.class);
            intent.putExtra("action", "start");
            startForegroundService(intent);
        }
        else {
             Intent intent = new Intent(this, MyService.class);
            intent.putExtra("action", "start");
            startService(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent(this, MyService.class);
            intent.putExtra("action", "stop");
            startForegroundService(intent);
        }
        else {
            Intent intent = new Intent(this, MyService.class);
            intent.putExtra("action", "stop");
            startService(intent);
        }
    }

}
MyService:  

public class MyService extends Service {

    int i =0;
    private String CHANNEL_ID = "2345";
    @Override
    public void onCreate() {
        super.onCreate();
    }

    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1000, createNotification());
        String action = intent.getExtras().getString("action"); 
        switch (action){
            case "start":
                final Handler handler = new Handler();
             Runnable runnable = new Runnable() {
             @Override
             public void run() {
                        myfunction();
                 handler.postDelayed(this, 1000);
            }
        };

            break;
            case "stop":
                stopfunction();
                break;
        }
        handler.postDelayed(runnable, 1000);
        return START_NOT_STICKY;
    }

    private void stopfunction() {
        stopSelf();
}

    private void myfunction() {
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("locations");
        myRef.child("location").setValue(i);
        i++;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void createChannel(){
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.infoTxt),
                NotificationManager.IMPORTANCE_HIGH);
        channel.setShowBadge(false);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        notificationManager.createNotificationChannel(channel);
    }

    private Notification createNotification(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            createChannel();
        }

        Intent notificationItent = new Intent(this, MainActivity.class);
        notificationItent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, 0, notificationItent, 0);

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setColor(ContextCompat.getColor(this, android.R.color.background_dark))
                .setContentIntent(intent)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setOnlyAlertOnce(true)
                .setContentTitle("GPS Location")
                .build();
    }
}

2 个答案:

答案 0 :(得分:1)

通常应将前景服务用于需要用户注意的任务,例如视觉过程。 使用Background服务

答案 1 :(得分:0)

我已经尝试了所有方法:服务,前台服务,广播接收器,jobSheduler,WorkerManager –没有任何帮助。然后,我发现这是华为的一项新功能,即“耗电量巨大的应用程序监视器”。除非用户为其授予特殊权限,否则它将杀死长时间在后台运行的每个应用程序。 执行此操作的路径: 设置->安全和隐私->位置服务->最近的位置请求:您的应用名称->电池->取消选中耗电的提示,应用启动:手动管理:检查所有三个位置:自动启动,二次启动,在以下位置运行背景。

我不知道有没有办法以编程方式执行此操作。我认为最好的方法是创建一种帮助活动,并向用户解释如果应用程序无法运行该怎么办。