public class AlwaysService extends Service {
public boolean threadIsTerminate = false;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
threadIsTerminate = true;
new Thread(() -> {
while (threadIsTerminate) {
runForever();
try {
Thread.sleep(2000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
final String id_channel = "Foreground Service ID";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id_channel, id_channel,
NotificationManager.IMPORTANCE_LOW);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this, id_channel)
.setContentTitle("Service Enabled").
setContentText("Service is running").
setSmallIcon(R.drawable.ic_launcher_foreground);
startForeground(1001, notification.build());
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
threadIsTerminate = false;
super.onDestroy();
}
private void runForever() {
String nameApp = isAppRunning(this);
Log.e("TAG", nameApp);
}
public static String isAppRunning(final Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = activityManager.getRunningTasks(1);
return runningTaskInfo.get(0).topActivity.getPackageName();
}
}
}
Mensaje en el Logcat:
2022-08-05 10:32:00.362 20677-20716/multiverse.crud_sqlite E/TAG: multiverse.crud_sqlite
2022-08-05 10:32:02.372 20677-20716/multiverse.crud_sqlite E/TAG: multiverse.crud_sqlite
2022-08-05 10:32:04.384 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home
2022-08-05 10:32:06.396 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home
2022-08-05 10:32:08.399 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home
2022-08-05 10:32:00.362 20677-20716/multiverse.crud_sqlite E/TAG: multiverse.crud_sqlite 2022-08-05 10:32:02.372 20677-20716/multiverse.crud_sqlite E/TAG: multiverse.crud_sqlite 2022-08-05 10:32:04.384 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home 2022-08-05 10:32:06.396 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home 2022-08-05 10:32:08.399 20677-20716/multiverse.crud_sqlite E/TAG: com.miui.home
Intent intent = new Intent(this, AlwaysService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
}