关闭

Activity与Service通信之信使(Messenger)

标签: android studioMessenger信使Service和Activity通信android
285人阅读 评论(0) 收藏 举报
分类:
一、通信原理
       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

效果:


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:73285次
    • 积分:1999
    • 等级:
    • 排名:第19714名
    • 原创:120篇
    • 转载:57篇
    • 译文:0篇
    • 评论:13条
    最新评论