Я создал фоновый сервис для регистрации SCREEN_ON и SCREEN_OFF с намерением перехватить событие, используя широковещательный приемник, но некоторое время по неизвестной причине мой сервис не передает намерение моему основному приложению.Для тестирования я сгенерировал лог-файл, используя десятисекундный таймер, что это мой фоновый сервис работает или нет.Который я прикрепил ниже.У меня проблема с тем, что моя фоновая служба останавливается некоторое время и запускается автоматически.
Это моя фоновая служба
public class MyBackgroundService extends Service {
BroadcastReceiver receiver;
private static final String LOG_TAG = "MyBackgroundService";
@Override
public void onCreate() {
super.onCreate();
Timber.i("Foreground Service OnCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timber.i("Start Foreground Service");
receiver = new ScreenStateReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
if (intent.getAction().equals(Constants.STARTFOREGROUND_ACTION)) {
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("text")
.setTicker("text")
.setContentText("text")
.setSmallIcon(R.drawable.logo_icon)
.setContentIntent(pendingIntent)
.setOngoing(true).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
startTimer();
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
Timber.i("Foreground Service onUnbind");
return super.onUnbind(intent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Timber.i("Foreground Service onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
stopForeground(true);
Timber.i("Foreground Service onDestroy");
stoptimertask();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 10000, 10000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Timber.i("Timer");
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
Это моя широковещательная рассылка
public class ScreenStateReceiver extends BroadcastReceiver {
public ScreenStateReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_SCREEN_OFF)){
Timber.i("Screen OFF");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Timber.i("Screen ON");
}
}
}
Menifest, объявление XML-файла
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".service.MyBackgroundService"/>
<receiver android:name=".receiver.ScreenStateReceiver" android:enabled="true" android:exported="true">
<intent-filter >
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
Я запускаю Службу с помощью намерения
Intent service = new Intent(getContext().getApplicationContext(), MyBackgroundService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
service.setAction(Constants.STARTFOREGROUND_ACTION);
getContext().getApplicationContext().startForegroundService(service);
}
else{
service.setAction(Constants.MAIN_ACTION);
getContext().getApplicationContext().startService(service);
}
Вот это изображение моего файла журнала ФАЙЛ ЛОГАЦИИ , используя этот файл журнала, вы можетевидеть, что фоновый сервис останавливается и запускается автоматически.Пожалуйста, помогите мне решить эту проблему.