Service详解(三)——实现通信之Messager

Messager使用场景:

1.需要IPC,不需要并发

服务端Service的代码:

package com.whhos.messagerservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

public class MessengerService extends Service {

    private Messenger mMessager = new Messenger(new Handler(){

        @Override
        public void handleMessage(Message msgFromClient) {

            Message msgToClient = Message.obtain(msgFromClient);
            switch (msgFromClient.what){
                case 1:
                    msgToClient.arg1 = msgFromClient.arg1+msgFromClient.arg2;
                    msgToClient.what = 1;

                        if(msgFromClient.replyTo == null){
                            Toast.makeText(getApplicationContext(),"空指针"+msgToClient.arg1,Toast.LENGTH_LONG).show();
                        }else {
                            Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_LONG).show();

                        }

                    try {
                        msgFromClient.replyTo.send(msgToClient);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }


                    break;
                default:
                    break;
            }
        }
    });

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mMessager.getBinder();
    }
}

服务端mainfest中Service注册的代码:

<service
            android:name=".MessengerService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.whhos.calservice"></action>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </service>

客户端Activity中的代码:

package com.whhos.messengerclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button btCal;
    private EditText etNum1;
    private EditText etNum2;
    private TextView tvResult;

    private Messenger serMessenger;

    private Messenger mMessenger = new Messenger(new Handler(){

        @Override
        public void handleMessage(Message msgFromServer) {

            switch (msgFromServer.what){

                case 1:
                    tvResult.setText(""+msgFromServer.arg1);


            }



        }
    });

    ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            serMessenger = new Messenger(service);



        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btCal =(Button) findViewById(R.id.cal);

        etNum1 = (EditText) findViewById(R.id.et_num1);
        etNum2 = (EditText) findViewById(R.id.et_num2);

        tvResult = (TextView) findViewById(R.id.tv_result);

        Intent intent = new Intent();
        intent.setAction("com.whhos.calservice");

intent.setPackage("com.whhos.messagerservice");

        bindService(intent,sc, Context.BIND_AUTO_CREATE);

        btCal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int num1 =Integer.parseInt(etNum1.getText().toString().trim()) ;
                int num2 =Integer.parseInt(etNum2.getText().toString().trim()) ;

                Message msgFromClient = Message.obtain();
                msgFromClient.what = 1;
                msgFromClient.arg1 = num1;
                msgFromClient.arg2 = num2;
                msgFromClient.replyTo = mMessenger;

                try {
                    serMessenger.send(msgFromClient);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }


            }
        });


    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
   >

    <EditText
        android:id="@+id/et_num1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/et_num2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/cal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="计算"/>
</LinearLayout>

 

转载于:https://my.oschina.net/whhos/blog/689221

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值