1 package com.googlecode.android_scripting.service;
2 
3 import android.app.Service;
4 import android.content.Intent;
5 import android.os.HandlerThread;
6 import android.os.IBinder;
7 import android.os.Messenger;
8 
9 import com.googlecode.android_scripting.facade.FacadeConfiguration;
10 import com.googlecode.android_scripting.facade.FacadeManagerFactory;
11 import com.googlecode.android_scripting.jsonrpc.RpcReceiverManagerFactory;
12 
13 /**
14  * FacadeService exposes SL4A's Facade methods through a {@link Service} so
15  * they can be invoked from third-party apps.
16  * <p>
17  * Example binding code:<br>
18  * {@code
19  *   Intent intent = new Intent();
20  *   intent.setPackage("com.googlecode.android_scripting");
21  *   intent.setAction("com.googlecode.android_scripting.service.FacadeService.ACTION_BIND");
22  *   sl4aService = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
23  * }
24  * Example using the service:<br>
25  * {@code
26  *   Bundle sl4aBundle = new Bundle;
27  *   bundle.putString{"sl4aMethod", "makeToast"};
28  *   bundle.putString{"message", "Hello World!"};
29  *   Message msg = Message.obtain(null, SL4A_ACTION);
30  *   msg.setData(sl4aBundle);
31  *   msg.replyTo = myReplyHandler; // Set a Messenger if you need the response
32  *   mSl4aService.send(msg);
33  * }
34  * <p>
35  * For more info on binding a {@link Service} using a {@link Messenger} please
36  * refer to Android's public developer documentation.
37  */
38 public class FacadeService extends Service {
39 
40     private RpcReceiverManagerFactory rpcReceiverManagerFactory;
41 
42     @Override
onBind(Intent intent)43     public IBinder onBind(Intent intent) {
44         if (rpcReceiverManagerFactory == null) {
45             rpcReceiverManagerFactory =
46                     new FacadeManagerFactory(FacadeConfiguration.getSdkLevel(), this, null,
47                             FacadeConfiguration.getFacadeClasses());
48         }
49         HandlerThread handlerThread = new HandlerThread("MessageHandlerThread");
50         handlerThread.start();
51         Messenger aMessenger = new Messenger(new MessageHandler(handlerThread,
52                 rpcReceiverManagerFactory));
53         return aMessenger.getBinder();
54     }
55 }
56