例如,播放檔案的檔名,或者控制訊息等等,
有幾個方法可以使用,
第一個就是利用Intent之間傳遞資料的方法,
在開始Service時,將資料帶入,
具體做法如下:
Intent i = new Intent(this,myServiceClass.class); i.putExtra("DATA_KEY1","my data"); i.putExtra("DATA_KEY2",1234); startService(i);在這裡我們放入"my data"這個字串和1234的數值,
那Service端要如何取出資料呢?
@Override public int onStartCommand(Intent intent, int flags, int startId) { String sData1=Intent.getStringExtra("DATA_KEY1"); int iData2=Intent.getIntExtra("DATA_KEY2",0); mServiceThread = new ServiceThread(); mServiceThread.start(); return START_STICKY ; }在onStartCommand()裡,我們可以取出傳過來的資料,
也就是說,sData1就是"my data",iData2就是1234,
你可以一直重覆呼叫startService(),傳入你需要的資料,
如果重覆呼叫startService(),onStartCommand()就會對應的被呼叫,
當然,在上面的例子,onStartCommand()裡面會執行new ServiceThread()和mServiceThread.start(), 這部份需要另外處理,避免也重覆到了...
另外還有一個常用的方式,就是利用bindService的機制,
public class myService extends Service { private ServiceThread mServiceThread; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return new myServiceLocalBinder(); } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { mServiceThread = new ServiceThread(); mServiceThread.start(); return START_STICKY ; } public class myServiceLocalBinder extends Binder { myService getService() { // Return this instance of LocalService so clients can call public methods return myService.this; } } public void SendData2Service(String s, int i) { //your action here } @Override public void onDestroy() { Log.d(TAG,"onDestroy()"); if (mServiceThread != null) mServiceThread.interrupt(); } private class ServiceThread extends Thread { @Override public void run() { super.run(); //your action here } } }在啓動Service的地方,修改如下:
myServiceClass myService=null; private ServiceConnection sMyServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myService = ((myServiceClass.myServiceLocalBinder) service).getService(); } }; public void StartMyService() { Intent i = new Intent(this, myService.class); bindService(i, sMyServiceConnection , BIND_AUTO_CREATE); startService(i); } public void StopMyService(){ Intent i = new Intent(this,myServiceClass.class); try{ unbindService(sMyServiceConnection); stopService(i); } catch (IllegalArgumentException e){ } }當你想要傳送資料給Service,可以利用myService.SendData2Service()
沒有留言:
張貼留言