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); try { mMessenger.send(msg); } catch (remoteexception e) { e.printstacktrace(); } break; case R.ID.button01: msg = Message.obtain(null,1,0); try { mMessenger.send(msg); } catch (remoteexception e) { e.printstacktrace(); } break; default: break; } }}
原文链接:http://blog.csdn.net/u012702547/article/details/46989417
以上就是本文的全部内容,希望对大家学习AndroID软件编程有所帮助。
总结以上是内存溢出为你收集整理的Android使用Messenger实现service与activity交互全部内容,希望文章能够帮你解决Android使用Messenger实现service与activity交互所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)