Как получить ACTION_SCREEN_OFF с «постоянно работающим» сервисом - PullRequest
0 голосов
/ 23 октября 2018

Я хочу создать приложение, которое устанавливает / сбрасывает таймер для воспроизведения песни, если мобильный телефон тратит 8 часов с выключенным экраном.

Я хочу создать службу, которая получает ACTION_SCREEN_OFF, но проблема в том,что, когда приложение убито из последних приложений, сервис убит.Я пытаюсь использовать START_STICKY, но служба не перезапускается (иногда вызывается onCreate, но не команда onStart).Я пытаюсь установить Manifest, но получатель должен быть зарегистрирован.

Сейчас я хочу, чтобы только получатель обнаружил ACTION_SCREEN_OFF.

У меня есть этот код: MainScreen.java (MainActivity)

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainScreen extends Activity implements View.OnClickListener{
    public static final String MSG_TAG = "NoSleepMore";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);

        findViewById(R.id.start_service_button).setOnClickListener(this);
        findViewById(R.id.stop_service_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        Intent intent = new Intent(getApplicationContext(), LockService.class);
        switch (v.getId()) {
            case R.id.start_service_button:
                Log.e(MSG_TAG,"Service started");
                //starts service for the given Intent
                startService(intent);
                break;
            case R.id.stop_service_button:
                Log.e(MSG_TAG,"Service stopped");
                //stops service for the given Intent
                stopService(intent);
                break;
        }
    }
}

LockService.java

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class LockService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(MainScreen.MSG_TAG, "onBind()" );
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(MainScreen.MSG_TAG, "Service Created");

        /* Filtrar Acciones Capturadas */
        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);

        // Listener
        final BroadcastReceiver mReceiver = new ScreenReceiver();

        // Registar Listener
        registerReceiver(mReceiver, filter);

        return Service.START_STICKY;
        //return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onCreate() {
        Log.i(MainScreen.MSG_TAG, "onCreate()");
    }

    @Override
    public void onDestroy() {
        Log.i(MainScreen.MSG_TAG, "onDestroy()");
    }
}

ScreenRecive.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        Log.i(MainScreen.MSG_TAG,"OnReceive->");
        // Log Handel
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            Log.i(MainScreen.MSG_TAG,"Screen action OFF");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            Log.i(MainScreen.MSG_TAG,"Screen action ON");
        }else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
            Log.e(MainScreen.MSG_TAG,"Action UserPresent");
        }
    }
}

AndroidManifext.xml

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

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

    <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">
        <activity android:name=".MainScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".ScreenReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_SCREEN_ON"/>
                <action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
                <action android:name="android.intent.action.ACTION_USER_PRESENT"/>
            </intent-filter>
        </receiver>

        <service android:name=".LockService" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </service>

    </application>
</manifest>

Основное действие - всего две кнопки.

Кстати, мне просто нужно запустить поверх Android 8.0.

...