Я выполняю задачу таймера в основном потоке и обновляю свой пользовательский интерфейс каждые 15 секунд. Я также запускаю еще одну задачу таймера в службе переднего плана (когда пользователь включает ее. Она предназначена для фоновых операций, таких как резервное копирование данных), содержащую уведомление, которое заставляет код задачи таймера продолжать работу, даже когда приложение закрыто. В любом случае я мог бы использовать службу переднего плана, но остановить эту задачу таймера.
Я уже делал что-то подобное, но это не сработало, поскольку говорится, что пользователь находится на экране из-за этого уведомления:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isInteractive();
if (!isScreenOn){
MainActivity.timer.cancel();
MainActivity.timer.purge();
}




Вы можете сделать это с помощью BroadcastReceiver.
вот некоторые настройки, использующие BroadcastReceiver.
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapp">
<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">
<!-- Other components -->
<receiver
android:name = ".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>
</application>
</manifest>
Добавьте это разрешение в манифест
<uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED" />
Файл ScreenStateReceiver.java
public class ScreenStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
MainActivity.stopTimerTask();
} else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
MainActivity.startTimerTaskIfNecessary();
}
}
}
// In your MainActivity
public static void startTimerTaskIfNecessary() {
if (timer == null) {
timer = new Timer();
// Schedule your task here
}
}
public static void stopTimerTask() {
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ScreenStateReceiver screenStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
if (screenStateReceiver == null) {
screenStateReceiver = new ScreenStateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(screenStateReceiver, filter);
}
}
@Override
protected void onPause() {
super.onPause();
if (screenStateReceiver != null) {
unregisterReceiver(screenStateReceiver);
screenStateReceiver = null;
}
}
}
Привет. Спасибо за ваш ответ. Я также добился того, чего хотел, используя onDestroy(). Я просто отменяю и очищаю таймер внутри него.