title: Accessing Android Context from java service
body: <p>I am attempting to create a java service that runs outside of the system server and would be started from boot, which based on configuration can monitor an Android device and listen for broadcasts. I have not been able to find documentation on how to write a long running java service that runs as a process that isn't started by zygote. I am trying to modify the platform and this service would be added to a custom system.img generated by rebuilding the Android source.</p>
  
  <p>The service would be started similar to the script used to run am from adb.</p>
  
  <pre><code>base=/system
  export CLASSPATH=$base/framework/am.jar
  exec app_process $base/bin com.android.commands.am.Am "$@"
  </code></pre>
  
  <p>The only examples that I have found trying to add daemons have been to implement fully <a href="https://groups.google.com/forum/?fromgroups=#!topic/android-porting/xH3ufHVCGk4" rel="nofollow">native services</a> that run on the device.</p>
  
  <p><a href="http://shop.oreilly.com/product/0636920021094.do?sortby=publicationDate" rel="nofollow">Embedded</a> Android describes Android Userspace and some of the native daemons that run there and how to create services and add them to init to start at device boot at least prior to Zygote and the System Server ect. </p>
  
  <pre><code>public class Monitor{
      public static void main(String [] args){
          new Monitor.run();
      }
      public void run(){
           Application app = new Application();
           Context con = app.getApplicationContext();
           BroadcastReceiver receiver = new BroadcastReceiver(){
               public void onReceive(Context context, Intent intent){
                   Log.i(TAG, "Received intent:"+ intent.getAction());
               }   
           }
           IntentFilter filter = new IntentFilter("android.intent.action.TIME_TICK")
      }
  }
  </code></pre>
  
  <p>I also tried this based on a snippet of code from the ActivityManagerService. 
      public class Monitor{
          private Context mContext;</p>
  
  <pre><code>    Monitor(){
          Looper.prepare()
          ActivityThread at = ActivityThread.systemMain();
          mContext = at.getSystemContext();
      }
      public static void main(String [] args){
          new Monitor.run();
      }
      public void run(){
           BroadcastReceiver receiver = new BroadcastReceiver(){
               public void onReceive(Context context, Intent intent){
                   Log.i(TAG, "Received intent:"+ intent.getAction());
               }   
           }
           IntentFilter  filter = new IntentFiler("android.intent.action.AIRPLANE_MODE");
           mContext.registerReceiver(receiver,filter);
      }
  }
  </code></pre>
  
  <p>I that intents/broadcasts can be generated from the commandline using adb and am but is there anyway to receive broadcasts. Any advice or suggestion is appreciated.</p>