实现客户端与服务端之间的交互
说明:
Messenger是信使的意思,从它的名字就可以了解到它充当着信差的角色。Android通过它实现跨进程通信,主要有客户端信使与服务端信使两种角色。当客户端调用bindService( )的时候,服务端会通过onBind( )方法将Ibinder传递给客户端,然后客户端通过ServiceConnection中的方法从Ibinder中获得服务端的信使,客户端可以通过服务端的信使把消息传递给服务端,最重要的一点是,客户端可以讲自己的信使即客户端信使放入消息中一起传递到服务端中,这样不仅可以从客户端传消息给服务端,还可以从服务端中返回信息给客户端。
服务端Server.apk
配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.server" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MessengerService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SERVICE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:text="服务端"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="100sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
服务
package com.android.server;
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;
/**
* 服务端
*/
public class MessengerService extends Service {
public static final int MSG_SUM = 1;
public static final int MSG_RET = 2;
public Messenger clientMessenger;
public Messenger serverMessenger = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MSG_SUM:
clientMessenger = msg.replyTo;
Message message = Message.obtain(null,MSG_RET);
message.arg1 = msg.arg1+msg.arg2;
try {
clientMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
handleMessage(msg);
}
}
});
@Override
public IBinder onBind(Intent intent) {
return serverMessenger.getBinder();
}
@Override
public boolean onUnbind(Intent intent) {
return true;
}
@Override
public void onRebind(Intent intent) {
}
}
界面
package com.android.server;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
客户端apk
配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.client" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:id="@+id/num1"
android:layout_width="100dp"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_toRightOf="@id/num1"
android:textSize="20sp"
/>
<EditText
android:id="@+id/num2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/plus"/>
<TextView
android:id="@+id/equal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:layout_toRightOf="@id/num2"
android:textSize="20sp"
/>
<EditText
android:id="@+id/sum"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/equal"
android:textSize="20sp"
android:editable="false"
/>
<Button
android:id="@+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:background="@color/colorPrimary"
android:layout_marginTop="80dp"
android:text="计算" />
</RelativeLayout>
界面
package com.android.client;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener {
public static final int MSG_SUM = 1;
public static final int MSG_RET = 2;
public EditText num1;
public EditText num2;
public EditText sum;
public Button btn;
//客户端信使
public Messenger clientMessenger = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MSG_RET:
sum.setText(msg.arg1+"");
break;
default:
super.handleMessage(msg);
}
}
});
//服务端信使
public Messenger serverMessenger;
public ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serverMessenger = new Messenger(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
serverMessenger = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.num1);
num2 = (EditText) findViewById(R.id.num2);
sum = (EditText) findViewById(R.id.sum);
btn = (Button) findViewById(R.id.calculate);
//绑定服务
Intent intent = new Intent();
intent.setAction("android.intent.action.SERVICE");
intent.setPackage("com.android.server");
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
btn.setOnClickListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
@Override
public void onClick(View v) {
if(num1.getText().toString().equals("") || num2.getText().toString().equals("") ){
Toast.makeText(this,"请输入数值",Toast.LENGTH_SHORT).show();
return;
}
Message message = Message.obtain(null,MSG_SUM,Integer.parseInt(num1.getText().toString()),Integer.parseInt(num2.getText().toString()));
message.replyTo = clientMessenger;
try {
serverMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}