編輯:關於Android編程
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軟件編程有所幫助。
有些Android手機中會帶有一些常用號碼的功能,比如訂餐電話、公共電話、航空機票,等等諸如此類的服務,點擊相應的號碼會自動彈出撥打電話的界面。那下面我們就一起來實現一個
今天在項目中用到了android中常用的RadioGroup、RadioButton、Spinner、EditText等控件,在此介紹一下它們的用法,希望對
當你在QQ空間直播開啟直播後,會收到粉絲們的禮物,也就是星星。這些星星可以兌換成收益直接提現嗎?其實這些都是可以提取出來的現金,那麼下面小編教大家QQ空間直
現在物聯網搞的轟轟烈烈的,小米的手環等一系列產品,下面我們就來研究一下小米手環的記步功能 工具類package com.zsl.bluetoothdemo.ble;im