亲宝软件园·资讯

展开

Messenger实现service与activity交互 Android使用Messenger实现service与activity交互

_江南一点雨 人气:0
想了解Android使用Messenger实现service与activity交互的相关内容吗,_江南一点雨在本文为您仔细讲解Messenger实现service与activity交互的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android,Messenger,service,activity,下面大家一起来学习吧。

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;
  }
 }
}

原文链接:http://blog.csdn.net/u012702547/article/details/46989417

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

加载全部内容

相关教程
猜你喜欢
用户评论