Android -- Messager與Service

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   io   使用   strong   ar   

如果你需要你的service和其他進程通訊,那麼你可以使用一個Messenger來提供這個介面。

這種方法允許你在不使用 AIDL的情況下,進行跨進程通訊IPC。

實現步驟                                                                              

下面是一個如何使用 Messenger的小總結:

  1. service實現一個 Handler 接收用戶端每一次調用的回調。

  2. Handler 用來建立一個Messenger對象,它是一個Handler的引用。

  3. Messenger建立一個 IBinder,service從 onBind()中把它返回給用戶端。

  4. 用戶端使用這個IBinder來執行個體化Messenger (service的Handler的引用),用戶端使用它來向service發送Message對象。

  5. service在它的Handler中接收每一個Message對象,在它的 handleMessage()方法中。

Code                                                                                   
public class MessengerService extends Service{    /** Command to the service to display a message */    static final int MSG_SAY_HELLO = 1;    /**     * Handler of incoming messages from clients.     */    class IncomingHandler extends Handler    {        @Override        public void handleMessage(Message msg)        {            switch (msg.what)            {                case MSG_SAY_HELLO:                    Toast.makeText(getApplicationContext(), "hello!",                            Toast.LENGTH_SHORT).show();                    break;                default:                    super.handleMessage(msg);            }        }    }    /**     * Target we publish for clients to send messages to IncomingHandler.     */    final Messenger mMessenger = new Messenger(new IncomingHandler());    /**     * When binding to the service, we return an interface to our messenger for     * sending messages to the service.     */    @Override    public IBinder onBind(Intent intent)    {        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT)                .show();        return mMessenger.getBinder();    }}

  注意 Handler中的 handleMessage() 方法是service接收到來的 Message並且決定做什麼的地方。

  用戶端需要做的僅僅是建立一個基於service所返回的 IBinder的 Messenger,然後用 send()方法發送資訊。

  比如,這裡有一個簡單的activity和service綁定並且發送資訊給service:

public class ActivityMessenger extends Activity{    /** Messenger for communicating with the service. */    Messenger mService = null;    /** Flag indicating whether we have called bind on the service. */    boolean mBound;    /**     * Class for interacting with the main interface of the service.     */    private ServiceConnection mConnection = new ServiceConnection()    {        public void onServiceConnected(ComponentName className, IBinder service)        {            // This is called when the connection with the service has been            // established, giving us the object we can use to            // interact with the service. We are communicating with the            // service using a Messenger, so here we get a client-side            // representation of that from the raw IBinder object.            mService = new Messenger(service);            mBound = true;        }        public void onServiceDisconnected(ComponentName className)        {            // This is called when the connection with the service has been            // unexpectedly disconnected -- that is, its process crashed.            mService = null;            mBound = false;        }    };    public void sayHello(View v)    {        if (!mBound)            return;        // Create and send a message to the service, using a supported ‘what‘        // value        Message msg = Message                .obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);        try        {            mService.send(msg);        }        catch (RemoteException e)        {            e.printStackTrace();        }    }    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);    }    @Override    protected void onStart()    {        super.onStart();        // Bind to the service        bindService(new Intent(this, MessengerService.class), mConnection,                Context.BIND_AUTO_CREATE);    }    @Override    protected void onStop()    {        super.onStop();        // Unbind from the service        if (mBound)        {            unbindService(mConnection);            mBound = false;        }    }}

  注意這個例子並沒有展示service如何響應用戶端,如果你想要service響應,你需要在用戶端中建立一個 Messenger。

  然後當用戶端接收到onServiceConnected()回調方法時,它會發送一個 Message到service,在它的send() 方法的replyTo參數中包含了用戶端的Messenger。

我是天王蓋地虎的分割線                                                             

 

 

參考:http://www.cnblogs.com/mengdd/tag/Android/default.html?page=4

Android -- Messager與Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.