欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用Messenger实现service与activity交互

程序员文章站 2024-03-04 12:00:23
service与activity交互的方式有多种,这里说说使用messenger来实现两者之间的交互。 service程序: public class mess...

service与activity交互的方式有多种,这里说说使用messenger来实现两者之间的交互。

service程序:

public class messengerservice extends service {

 final messenger mmessenger = new messenger(new incominghandler());
 @override
 public ibinder onbind(intent intent) {
  return mmessenger.getbinder();
 }

 @suppresslint("handlerleak")
 class incominghandler extends handler {

  @override
  public void handlemessage(message msg) {
   switch (msg.what) {
   case 0:
    toast.maketext(messengerservice.this,"hello lenve!", toast.length_long).show();
    break;
   case 1:
    toast.maketext(messengerservice.this,"hello lenve!hello world!", toast.length_long).show();
    break;
   default:
    break;
   }
  }

 }
}

mainactivity.javal:

public class mainactivity extends activity {

 private messenger mmessenger;
 private serviceconnection conn;
 private intent intent;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  intent = new intent(this,messengerservice.class);
  conn = new serviceconnection() {

   @override
   public void onservicedisconnected(componentname name) {
    mmessenger = null;
   }

   @override
   public void onserviceconnected(componentname name, ibinder service) {
    mmessenger = new messenger(service);
   }
  };
 }



 @override
 protected void onstart() {
  super.onstart();
  bindservice(intent, conn, bind_auto_create);
 }



 @override
 protected void onstop() {
  super.onstop();
  unbindservice(conn);
 }



 public void onclick(view v){
  message msg = null;
  switch (v.getid()) {
  case r.id.button1:
   msg = message.obtain(null, 0, 0, 0);
   try {
    mmessenger.send(msg);
   } catch (remoteexception e) {
    e.printstacktrace();
   }
   break;
  case r.id.button01:
   msg = message.obtain(null, 1, 0, 0);
   try {
    mmessenger.send(msg);
   } catch (remoteexception e) {
    e.printstacktrace();
   }
   break;
  default:
   break;
  }
 }
}

原文链接:

以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。