androidx.lifecycle.ProcessLifecycleOwner Java Examples

The following examples show how to use androidx.lifecycle.ProcessLifecycleOwner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApplicationContext.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();
  Log.i(TAG, "onCreate()");
  initializeSecurityProvider();
  initializeTypingStatusRepository();
  initializeTypingStatusSender();
  initializeRingRtc();
  initializeBlobProvider();
  ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

  if (Build.VERSION.SDK_INT < 21) {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
  }

  initializePassphraseLock();
}
 
Example #2
Source File: HomeActivity.java    From zap-android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //NFC
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    mHandler = new Handler();

    mUnlockDialog = buildUnlockDialog();

    // Register observer to detect if app goes to background
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

    // Set wallet fragment as beginning fragment
    mFt = getSupportFragmentManager().beginTransaction();
    mCurrentFragment = new WalletFragment();
    mFt.replace(R.id.mainContent, mCurrentFragment);
    mFt.commit();

    // Setup Listener
    BottomNavigationView navigation = findViewById(R.id.mainNavigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
 
Example #3
Source File: App.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Timber.plant(BuildConfig.DEBUG ? new DebugTree() : new ReleaseTree());
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

    if (BuildConfig.DEBUG)
        Stetho.initializeWithDefaults(this);

    Mapbox.getInstance(this, BuildConfig.MAPBOX_ACCESS_TOKEN);

    Fabric.with(this, new Crashlytics());

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        upgradeSecurityProviderSync();

    setUpAppComponent();
    setUpServerComponent();
    setUpRxPlugin();
}
 
Example #4
Source File: BaseApplication.java    From shinny-futures-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    sContext = getApplicationContext();
    sDataManager = DataManager.getInstance();
    mMDURLs = new ArrayList<>();
    mTDURLs = new ArrayList<>();
    mAppLifecycleObserver = new AppLifecycleObserver();
    sBackGround = false;
    mLocalBroadcastManager = LocalBroadcastManager.getInstance(sContext);
    ProcessLifecycleOwner.get().getLifecycle().addObserver(mAppLifecycleObserver);

    initAppVersion();
    initTMDUrl();
    initDefaultConfig();
    initThirdParty();
    downloadLatestJsonFile();
}
 
Example #5
Source File: AppLifecycleIntegration.java    From sentry-android with MIT License 5 votes vote down vote up
@Override
public void close() throws IOException {
  if (watcher != null) {
    ProcessLifecycleOwner.get().getLifecycle().removeObserver(watcher);
    watcher = null;
    if (options != null) {
      options.getLogger().log(SentryLevel.DEBUG, "AppLifecycleIntegration removed.");
    }
  }
}
 
Example #6
Source File: AddAccountActivity.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
private void waitForForeground(Runnable r, long timeout) {
    if (timeout <= 0) {
        throw new RuntimeException("Timed out waiting for foreground.");
    }
    boolean isAppInForeground =
        ProcessLifecycleOwner.get().getLifecycle().getCurrentState().isAtLeast(STARTED);
    if (isAppInForeground) {
        r.run();
    } else {
        new Handler().postDelayed(
            () -> waitForForeground(r, timeout - WAIT_FOR_FOREGROUND_DELAY_MS),
            WAIT_FOR_FOREGROUND_DELAY_MS);
    }
}
 
Example #7
Source File: MageApplication.java    From mage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();

	//This ensures the singleton is created with the correct context, which needs to be the
	//application context
	DaoStore.getInstance(this.getApplicationContext());
	LayerHelper.getInstance(this.getApplicationContext());
	StaticFeatureHelper.getInstance(this.getApplicationContext());

	ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

	HttpClientManager.initialize(this);

	// setup the screen unlock stuff
	registerReceiver(ScreenChangeReceiver.getInstance(), new IntentFilter(Intent.ACTION_SCREEN_ON));

	registerActivityLifecycleCallbacks(this);

	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	int dayNightTheme = preferences.getInt(getResources().getString(R.string.dayNightThemeKey), getResources().getInteger(R.integer.dayNightThemeDefaultValue));
	AppCompatDelegate.setDefaultNightMode(dayNightTheme);

	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		NotificationChannel channel = new NotificationChannel(MAGE_NOTIFICATION_CHANNEL_ID,"MAGE", NotificationManager.IMPORTANCE_LOW);
		channel.setShowBadge(true);
		notificationManager.createNotificationChannel(channel);

		NotificationChannel observationChannel = new NotificationChannel(MAGE_OBSERVATION_NOTIFICATION_CHANNEL_ID,"MAGE Observations", NotificationManager.IMPORTANCE_HIGH);
		observationChannel.setShowBadge(true);
		notificationManager.createNotificationChannel(observationChannel);
	}
}
 
Example #8
Source File: VoiceActivity.java    From voice-quickstart-android with MIT License 5 votes vote down vote up
private boolean isAppVisible() {
    return ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .getCurrentState()
            .isAtLeast(Lifecycle.State.STARTED);
}
 
Example #9
Source File: IncomingCallNotificationService.java    From voice-quickstart-android with MIT License 5 votes vote down vote up
private boolean isAppVisible() {
    return ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .getCurrentState()
            .isAtLeast(Lifecycle.State.STARTED);
}
 
Example #10
Source File: CustomDeviceActivity.java    From voice-quickstart-android with MIT License 5 votes vote down vote up
private boolean isAppVisible() {
    return ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .getCurrentState()
            .isAtLeast(Lifecycle.State.STARTED);
}
 
Example #11
Source File: HomeActivity.java    From zap-android with MIT License 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    stopListenersAndSchedules();
    // Remove observer to detect if app goes to background
    ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
}
 
Example #12
Source File: WearMouseApp.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    hidDataSender = HidDataSender.getInstance();
    settingsUtil = new SettingsUtil(this);
    ProcessLifecycleOwner.get().getLifecycle().addObserver(lifecycleObserver);
}
 
Example #13
Source File: ArcusApplication.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
private void setupLifecycleListener() {
    ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .addObserver(new LifecycleObserver() {
                @OnLifecycleEvent(Lifecycle.Event.ON_START)
                public void onForeground() {
                    NetworkConnectionMonitor.getInstance().startListening(ArcusApplication.this);

                    // Go back to 30-second timeout
                    useNormalTimeoutDelay();

                    logger.debug("Application is resumed, cancelling connection close.");
                    handler.removeCallbacks(closeCorneaRunnable);
                }

                @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
                public void onBackground() {
                    logger.debug("Application is backgrounded, posting delayed connection close.");
                    handler.postDelayed(closeCorneaRunnable, DELAY_BEFORE_CLOSE_MS);
                    NetworkConnectionMonitor.getInstance().stopListening(ArcusApplication.this);
                }
            });
}
 
Example #14
Source File: ConversationListFragment.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private void initializeViewModel() {
  viewModel = ViewModelProviders.of(this, new ConversationListViewModel.Factory()).get(ConversationListViewModel.class);

  viewModel.getSearchResult().observe(this, this::onSearchResultChanged);
  viewModel.getMegaphone().observe(this, this::onMegaphoneChanged);

  ProcessLifecycleOwner.get().getLifecycle().addObserver(new DefaultLifecycleObserver() {
    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
      viewModel.onVisible();
    }
  });
}
 
Example #15
Source File: SimpleAppLifecycleTestActivity.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * stop process observer
 */
public static void stopProcessObserver() {
    ProcessLifecycleOwner.get().getLifecycle().removeObserver(sProcessObserver);
}
 
Example #16
Source File: ZephyrApplication.java    From zephyr with MIT License 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    sInstance = this;

    sApplicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();

    sApplicationComponent.inject(ZephyrApplication.this);
    sApplicationComponent.init();

    registerActivityLifecycleCallbacks(new ZephyrLifecycleLogger());
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

    EventBus.builder().logNoSubscriberMessages(false).installDefaultEventBus();

    if (configManager.isFirebaseEnabled()) {
        FirebaseApp.initializeApp(this);
    } else {
        logger.log(LogLevel.WARNING, LOG_TAG, "Firebase disabled, some features will be limited or disabled.");
    }

    if (configManager.isFirebasePerformanceMonitoringEnabled()) {
        FirebasePerformance.getInstance().setPerformanceCollectionEnabled(true);
    }

    FirebaseCrashlytics firebaseCrashlytics = FirebaseCrashlytics.getInstance();
    if (privacyManager.isCrashReportingEnabled()) {
        firebaseCrashlytics.setCrashlyticsCollectionEnabled(true);
        firebaseCrashlytics.setUserId(privacyManager.getUuid());
        sCrashReportingInitialized = true;
    } else {
        firebaseCrashlytics.setCrashlyticsCollectionEnabled(false);
        logger.log(LogLevel.WARNING, LOG_TAG, "Crashlytics disabled.");
    }

    if (!BuildConfig.PROPS_SET) {
        logger.log(LogLevel.WARNING, LOG_TAG, "Secret properties not set! Some features will be limited or disabled.");
    }

    if (flipperManager.isInitialized()) {
        logger.log(LogLevel.INFO, LOG_TAG, "Flipper initialized.");
    }

    logger.log(LogLevel.DEBUG, LOG_TAG, "Zephyr %s (%s - %s) started.", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, BuildConfig.GIT_HASH);

    themeManager.setDefaultNightMode();

    sApplicationComponent.notificationsManager().createNotificationChannels();

    workManager.initWork();

    verifyConnectionStatus();

    // Check for updates from AppCenter if beta.
    // TODO: Refactor to be generic and to support other tracks.
    if (BuildConfig.PROPS_SET && configManager.isBeta()) {
        AppCenter.start(this, BuildConfig.APP_CENTER_SECRET, Distribute.class);
    } else if (!BuildConfig.PROPS_SET && configManager.isBeta()) {
        logger.log(LogLevel.WARNING, LOG_TAG, "AppCenter update check disabled -- APP_CENTER_SECRET not set!");
    }

    if (configManager.isDiscoveryEnabled()) {
        logger.log(LogLevel.INFO, LOG_TAG, "Starting DiscoveryManager.");
        discoveryManager.start();
    }

    // Track version code
    preferenceManager.getInt(PreferenceKeys.PREF_LAST_KNOWN_APP_VERSION, BuildConfigUtils.getVersionCode());
}
 
Example #17
Source File: TindroidApp.java    From tindroid with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
        sAppVersion = pi.versionName;
        sAppBuild = pi.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        Log.w(TAG, "Failed to retrieve app version", e);
    }

    // Disable Crashlytics for debug builds.
    FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG);

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String token = intent.getStringExtra("token");
            if (token != null && !token.equals("") && sTinodeCache != null) {
                sTinodeCache.setDeviceToken(token);
            }
        }
    };
    LocalBroadcastManager.getInstance(this).registerReceiver(br, new IntentFilter("FCM_REFRESH_TOKEN"));

    createNotificationChannel();

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

    // Listen to connectivity changes.
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    if (cm == null) {
        return;
    }
    NetworkRequest req = new NetworkRequest.
            Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    cm.registerNetworkCallback(req, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                if (sTinodeCache != null) {
                    sTinodeCache.reconnectNow(true, false, false);
                }
            }
        });

    // Check if preferences already exist. If not, create them.
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    sServerHost = pref.getString("pref_hostName", null);
    if (TextUtils.isEmpty(sServerHost)) {
        // No preferences found. Save default values.
        SharedPreferences.Editor editor = pref.edit();
        sServerHost = getDefaultHostName(this);
        sUseTLS = getDefaultTLS();
        editor.putString("pref_hostName", sServerHost);
        editor.putBoolean("pref_useTLS", sUseTLS);
        editor.apply();
    } else {
        sUseTLS = pref.getBoolean("pref_useTLS", false);
    }
}
 
Example #18
Source File: ApplicationContext.java    From deltachat-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();

  // if (LeakCanary.isInAnalyzerProcess(this)) {
  //   // This process is dedicated to LeakCanary for heap analysis.
  //   // You should not init your app in this process.
  //   return;
  // }
  // LeakCanary.install(this);

  Log.i("DeltaChat", "++++++++++++++++++ ApplicationContext.onCreate() ++++++++++++++++++");

  System.loadLibrary("native-utils");
  dcContext = new ApplicationDcContext(this);

  new ForegroundDetector(ApplicationContext.getInstance(this));

  BroadcastReceiver networkStateReceiver = new NetworkStateReceiver();
  registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));

  KeepAliveService.maybeStartSelf(this);

  initializeRandomNumberFix();
  initializeLogging();
  initializeJobManager();
  ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
  InChatSounds.getInstance(this);

  dcLocationManager = new DcLocationManager(this);
  try {
    DynamicLanguage.setContextLocale(this, DynamicLanguage.getSelectedLocale(this));
  }
  catch (Exception e) {
    e.printStackTrace();
  }

  dcContext.setStockTranslations();

  IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
  registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          dcContext.setStockTranslations();
      }
  }, filter);

  // MAYBE TODO: i think the ApplicationContext is also created
  // when the app is stated by FetchWorker timeouts.
  // in this case, the normal threads shall not be started.
  Constraints constraints = new Constraints.Builder()
          .setRequiredNetworkType(NetworkType.CONNECTED)
          .build();
  PeriodicWorkRequest fetchWorkRequest = new PeriodicWorkRequest.Builder(
          FetchWorker.class,
          PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, // usually 15 minutes
          TimeUnit.MILLISECONDS,
          PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, // the start may be preferred by up to 5 minutes, so we run every 10-15 minutes
          TimeUnit.MILLISECONDS)
          .setConstraints(constraints)
          .build();
  WorkManager.getInstance(this).enqueueUniquePeriodicWork(
          "FetchWorker",
          ExistingPeriodicWorkPolicy.KEEP,
          fetchWorkRequest);
}
 
Example #19
Source File: SimpleAppLifecycleTestActivity.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * start process observer
 */
public static void startProcessObserver() {
    ProcessLifecycleOwner.get().getLifecycle().addObserver(sProcessObserver);
}
 
Example #20
Source File: AppLifecycleIntegration.java    From sentry-android with MIT License 4 votes vote down vote up
@Override
public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) {
  Objects.requireNonNull(hub, "Hub is required");
  this.options =
      Objects.requireNonNull(
          (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
          "SentryAndroidOptions is required");

  this.options
      .getLogger()
      .log(
          SentryLevel.DEBUG,
          "enableSessionTracking enabled: %s",
          this.options.isEnableSessionTracking());

  this.options
      .getLogger()
      .log(
          SentryLevel.DEBUG,
          "enableAppLifecycleBreadcrumbs enabled: %s",
          this.options.isEnableAppLifecycleBreadcrumbs());

  if (this.options.isEnableSessionTracking() || this.options.isEnableAppLifecycleBreadcrumbs()) {
    try {
      Class.forName("androidx.lifecycle.DefaultLifecycleObserver");
      Class.forName("androidx.lifecycle.ProcessLifecycleOwner");
      watcher =
          new LifecycleWatcher(
              hub,
              this.options.getSessionTrackingIntervalMillis(),
              this.options.isEnableSessionTracking(),
              this.options.isEnableAppLifecycleBreadcrumbs());
      ProcessLifecycleOwner.get().getLifecycle().addObserver(watcher);

      options.getLogger().log(SentryLevel.DEBUG, "AppLifecycleIntegration installed.");
    } catch (ClassNotFoundException e) {
      options
          .getLogger()
          .log(
              SentryLevel.INFO,
              "androidx.lifecycle is not available, AppLifecycleIntegration won't be installed",
              e);
    }
  }
}
 
Example #21
Source File: HentoidApp.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Fabric.with(this, new Crashlytics());

    // Fix the SSLHandshake error with okhttp on Android 4.1-4.4 when server only supports TLS1.2
    // see https://github.com/square/okhttp/issues/2372 for more information
    try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
    } catch (Exception e) {
        Timber.e(e, "Google Play ProviderInstaller exception");
    }

    // Init datetime
    AndroidThreeTen.init(this);

    // Timber
    if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree());
    Timber.plant(new CrashlyticsTree());

    // Prefs
    Preferences.init(this);
    Preferences.performHousekeeping();

    // Image viewer
    // Needs ARGB_8888 to be able to resize images using RenderScript
    // (defaults to Bitmap.Config.RGB_565 if not set)
    CustomSubsamplingScaleImageView.setPreferredBitmapConfig(Bitmap.Config.ARGB_8888);

    // Init version number on first run
    if (0 == Preferences.getLastKnownAppVersionCode())
        Preferences.setLastKnownAppVersionCode(BuildConfig.VERSION_CODE);

    // Firebase
    boolean isAnalyticsEnabled = Preferences.isAnalyticsEnabled();
    FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(isAnalyticsEnabled);

    // DB housekeeping
    performDatabaseHousekeeping();

    // Init notification channels
    UpdateNotificationChannel.init(this);
    DownloadNotificationChannel.init(this);
    MaintenanceNotificationChannel.init(this);

    // Clears all previous notifications
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (manager != null) manager.cancelAll();

    // Run app update checks
    if (Preferences.isAutomaticUpdateEnabled()) {
        Intent intent = UpdateCheckService.makeIntent(this, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    // Build Android shortcuts
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        ShortcutHelper.buildShortcuts(this);
    }

    // Send stats to Firebase
    FirebaseAnalytics.getInstance(this).setUserProperty("color_theme", Integer.toString(Preferences.getColorTheme()));
    FirebaseAnalytics.getInstance(this).setUserProperty("endless", Boolean.toString(Preferences.getEndlessScroll()));

    // Plug the lifecycle listener to handle locking
    ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifeCycleListener());

    // Set RxJava's default error handler for unprocessed network and IO errors
    RxJavaPlugins.setErrorHandler(e -> {
        if (e instanceof UndeliverableException) {
            e = e.getCause();
        }
        if (e instanceof IOException) {
            // fine, irrelevant network problem or API that throws on cancellation
            return;
        }
        if (e instanceof InterruptedException) {
            // fine, some blocking code was interrupted by a dispose call
            return;
        }
        Timber.w(e, "Undeliverable exception received, not sure what to do");
    });
}