Launch service from app start, not activity

旧时模样 提交于 2019-12-05 23:12:34

问题


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, i.e. 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.


回答1:


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();
   }

}


来源:https://stackoverflow.com/questions/12817311/launch-service-from-app-start-not-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!