Paste: BaseGlobalService

Author: 5
Mode: factor
Date: Thu, 21 Sep 2023 02:39:29
Plain Text |
package com.akubela.panel.service.base;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;

import java.util.ArrayList;

public class BaseGlobalService extends Service implements LifecycleOwner, ViewModelStoreOwner {

    protected LifecycleRegistry mLifecycleRegistry = null;

    private final ArrayList<AlertDialog> mDialogs = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        initLifecycle();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        return super.onStartCommand(intent, flags, startId);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return new ViewModelStore();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mLifecycleRegistry) {
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
            mLifecycleRegistry = null;
        }
        dismissAll();
    }

    protected void initLifecycle() {
        if (null == mLifecycleRegistry) {
            mLifecycleRegistry = new LifecycleRegistry(this);
        }

        mLifecycleRegistry.addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    getViewModelStore().clear();
                }
            }
        });
    }

    protected void addToDismissList(AlertDialog dialog) {
        if (!mDialogs.contains(dialog)) {
            mDialogs.add(dialog);
        }
    }

    protected void dismissExcept(AlertDialog dialog) {
        for (AlertDialog d : mDialogs) {
            if (d != dialog) {
                dismissDialog(d);
            }
        }
    }

    protected void dismissAll(){
        dismissExcept(null);
    }


    protected void dismissDialog(AlertDialog dialog) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

New Annotation

Summary:
Author:
Mode:
Body: