Home > database >  How do I start an activity in the background and close it immediately?
How do I start an activity in the background and close it immediately?

Time:10-04

So I have a SettingsActivity that will launch my SettingsFragment when the user clicks on the settings button in MainActivity. For my SettingsFragment, when the user launches the screen for the first time, it will activate the AlarmManager I have set it up. This defaults to on when the user signs in for the first time. The user does have the option to turn off notifications.

Now, if the user never goes to the settings screen, it will never activate the AlarmManager. How do I start the SettingsActivity in the background where it doesn't actually show the UI of the SettingsActivity or SettingsFragment and then close the SettingsActivity/SettingsFragment immediately so it's not running in the background forever? I just want to start it up when the user logs in for the first time or logs back in again so the app knows the state of the AlarmManager whether it's on or off. If it doesn't know the state, the user will never get any notifications until the user manually clicks on the settings button.

CodePudding user response:

First, understand the activity lifecycle: https://developer.android.com/guide/components/activities/activity-lifecycle

You can finish your activity at any time (for example onResume()) by calling finish(). You can also use a Timer, a Handler or an Alarm to finish() it at a different time.

In order to make your activity transparent / invisible, don't inflate it with any kind of layout. I would also recommend adding the following lines to the manifest for your activity:

android:launchMode="singleInstance"
android:excludeFromRecents="true"

Regarding the ability to start this activity without any kind of user interaction... you may want to use a Service and startActivity() from there (and potentially also finish() it).

That said, from what you are describing I think you are designing this in a very complicated way and may run yourself down a rabbit hole.

CodePudding user response:

You should let your SettingActivity be your SettingActivity.

When you not use SQLITE or something else to store settings: https://developer.android.com/training/data-storage/shared-preferences

Putting all your Code into the SettingFragment should not be your Solution. You could something like this do:

return this.sharedPreferences.getBoolean(context.getResources().getString(R.string.preference_stateAlarmmanager), false); // returns false if the preference not yet exists

Just read your property and execute your code to start the alarmmanager in case it's true

  • Related