ABang的博客

踏入IT行业,总得留点什么......

Activity与Service通信之信使(Messenger)
一、通信原理
       Messenger翻译过来指的是信使,它引用了一个Handler对象,别人可以通过Messenger向它发送消息(使用mMessenger.send(Message msg)方法)。该类允许跨进程间基于Message通信,在服务端使用Handler创建一个 Messenger,客户端只要获得这个服务端的Messenger对象就可以与服务端通信了。
      使用步骤:           

                (1). 在Server端创建信使对象。

               mMessenger = new Messenger(mHandler)

        (2). Server端的onBind()方法返回一个binder对象。

               return mMessenger.getBinder();

        (3). Client端使用bindService()绑定Server端,通过public void onServiceConnected(ComponentName name, IBinder service)方法获取服务端的信使对象

        (4). Client端使用返回的binder对象得到Server端信使。

二、核心代码:

Service端:

public class MessengerService extends Service{

private static final int TIME = 1;
public static final int TEST = 0;
private int i = 0;
private Timer mTimer = null;

private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEST:
/** 获取客户端信使*/
cMessenger = msg.replyTo;
/** 执行计时器*/
mTimer.schedule(new MyTimerTask(), 1000,TIME * 1000);
break;
default:
break;
}
}
};

/** 服务端信使*/
private Messenger mMessenger = new Messenger(mHandler);
/** 客户端信使*/
private Messenger cMessenger = null;


@Override
public IBinder onBind(Intent intent) {
//派遣一个信使到服务端
return mMessenger.getBinder();
}

@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
}


class MyTimerTask extends TimerTask {
@Override
public void run() {
if (i == 100) {
i = 0;
}
try {
Message message = Message.obtain(null, MessengerService.TEST,i, 0);
cMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
i++;
}
}


@Override
public void onDestroy() {
super.onDestroy();
if(mTimer!=null){
mTimer.cancel();
mTimer = null;
}
}

}
Activity:

import android.app.Activity;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import testndk.testservice.service.MessengerService;
public class MessageActivity extends Activity {

private boolean mIsBind;
private Button startBtn = null;
private Button stopBtn = null;
private TextView mTextView = null;
/** 从服务端获取的信使*/
private Messenger rMessenger = null;
/** 本地信使*/
private Messenger mMessenger = null;

private Intent intent = null;
private ProgressBar mProgressBar = null;

private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MessengerService.TEST:
int curLoad = msg.arg1;
mTextView.setText(curLoad+"%");
mProgressBar.setProgress(curLoad);
break;

default:
break;
}
}
};
private ServiceConnection serConn = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
rMessenger = null;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
rMessenger = new Messenger(service);//get the object of remote service
mMessenger = new Messenger(mHandler);//initial the object of local service
sendMessage();
}
};

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

intent = new Intent(this,MessengerService.class);
mProgressBar = (ProgressBar)findViewById(R.id.myProgressBar);
mProgressBar.setMax(100);
mTextView = (TextView)findViewById(R.id.loading_Tv);
startBtn = (Button)findViewById(R.id.start_Btn);
stopBtn = (Button)findViewById(R.id.stop_Btn);
startBtn.setOnClickListener(new ButtonClickListener());
stopBtn.setOnClickListener(new ButtonClickListener());

}


class ButtonClickListener implements OnClickListener {

@Override
public void onClick(View v) {
if (startBtn == v) {
mIsBind = bindService(intent, serConn, Context.BIND_AUTO_CREATE);//if bind success return true
} else if (stopBtn == v) {
if(mIsBind){
unbindService(serConn);
mIsBind = false;
}
}
}

}
/** 向服务端发信息*/
private void sendMessage() {
Message msg = Message.obtain(null, MessengerService.TEST);//MessengerService.TEST=0
msg.replyTo = mMessenger;
try {
rMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
注意:在配置文件中不要忘记注册服务:

<service android:name=".service.MessengerService">
</service>

源码下载地址:

http://download.csdn.net/detail/lu1024188315/9537991

效果:


阅读更多
版权声明:请尊重劳动成果,转载请注明来处:Abang的博客 http://blog.csdn.net/lu1024188315,如果您有不同意见,请尽情留言 https://blog.csdn.net/lu1024188315/article/details/51557087
个人分类: Service
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Activity与Service通信之信使(Messenger)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭