简体   繁体   中英

Launch service from app start, not activity

I want to launch a Service when the app is launched instead of an Activity; and then said Service will launch an Activity . I need to do this because my app needs to be running ALWAYS, and when I say ALWAYS I mean ALWAYS. And the only way I've managed to avoid the OS killing my app is by starting a service as Sticky and should Android kill either my Activity or my Service I'll restart them right away.

I found this question but the top answer seems rather clumsy, any one has a better idea?

PS: I know this doesn't look like a very friendly app but this is a very specific research scenario and it's not intended for regular users, ie the phone is solely used for this purpose; but even if memory is dedicated to my app Android keeps killing it every now and then... Any doubts I might have had about Android's purported strict memory management scheme are now gone.

In general Activity does NOT have to show any UI - it usually does but it is NOT mandatory . So you can simply set app's starting point to your "invisible" activity. And invisible means either themed as

android:theme="@android:style/Theme.NoDisplay"

or simply your code will not do any setContentView() and once it's job is done in your onCreate() , you start another activity and terminate this one with finish() - and no UI would pop up from that activity - that way you can easily benefit from doing your job in activity subclass (which may be simpler for some tasks) and still do not need any UI:

public void onCreate(Bundle bundle) {
   super.onCreate(bundle);

   // [... do your job here...]

   // we're done, so let's jump to another acitivity
   // this can be skipped if you do not want to jump anywhere

   Intenet intent = new Intent(....)
   ...

   try {
      startActivity( intent );

      // finish him
      finish();

   } catch ( Exception e ) {
      e.printStackTrace();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM