android service是后台运行的服务,没有界面。比如我们后台播放音乐就可以启动一个服务,service和其他组件一样是运行在主线程的,所以不能进行耗时的操作,不过我们可以开启一个线程来支持耗时操作
服务一般分为两种:
本地服务:Localhost Serviece是应用程序内部的服务,程序通过context.startService()来启动服务,通过调用Context.stopService()来关闭服务,内部也可以通过调用Service.stopSelf或者 Service.stopSelfResult()来自己停止,无论调用的多少次的,startService()只需要调用一次stopService();
2:远程服务, 远程服务是android程序内部的,可以吧接口暴露,让其他程序调用。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。
context.startService() ->onCreate()- >onStart()->Service running--调用context.stopService() ->onDestroy()
context.bindService()->onCreate()->onBind()->Service running--调用>onUnbind() ->onDestroy()从上诉可以知道分别对应本地的,,以及远程的,也对应不同的方式启动这个服务。
下面看看第一个案例:最基本的service案例:
启动服务来后台播放music
public class PlayMusicService extends Activity implements OnClickListener{ private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button closeBtn; private Button exitBtn; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.music_service); playBtn=(Button) findViewById(R.id.play); stopBtn=(Button) findViewById(R.id.stop); pauseBtn=(Button) findViewById(R.id.pause); closeBtn=(Button) findViewById(R.id.close); exitBtn=(Button) findViewById(R.id.exit); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); closeBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); } @Override public void onClick(View v) { int op=-1; intent=new Intent("com.musicService"); switch (v.getId()) { case R.id.play: op=1; break; case R.id.stop: // stop music op=2; break; case R.id.pause: // pause music op=3; break; case R.id.close: // close activity this.finish(); break; case R.id.exit: op=4; stopService(intent); this.finish(); break; } Bundle bundle=new Bundle(); bundle.putInt("op", op); intent.putExtras(bundle); startService(intent); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(intent!=null){ stopService(intent); } } }
public class MusicService extends Service{ private static final String TAG = "MyService"; private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Log.v(TAG, "onCreate"); super.onCreate(); if(mediaPlayer==null){ mediaPlayer=MediaPlayer.create(this, R.raw.tmp); mediaPlayer.setLooping(false); } } @Override public void onDestroy() { Log.v(TAG, "onDestroy"); Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } } @Override public void onStart(Intent intent, int startId) { Log.v(TAG, "onStart"); if(intent!=null){ Bundle bundle=intent.getExtras(); if(bundle!=null){ int op=bundle.getInt("op"); switch (op) { case 1: play(); break; case 2: stop(); break; case 3: pause(); break; } } } } public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } private void stop() { // TODO Auto-generated method stub if(mediaPlayer!=null){ mediaPlayer.stop(); try { mediaPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void play() { // TODO Auto-generated method stub if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); } } }
<activity android:name="com.example.myservicetest.service.PlayMusicService" android:label="@string/app_name" /> <service android:name=".service.MusicService" android:enabled="true" > <intent-filter> <action android:name="com.musicService" /> </intent-filter> </service>
<activity android:name="com.example.myservicetest.receiver.PlayMusicRecevicer" android:label="@string/app_name" /> <receiver android:name=".receiver.MusicReceiver" > <intent-filter> <action android:name="com.musicReceiver" /> </intent-filter> </receiver>
public class PlayMusicRecevicer extends Activity implements OnClickListener { private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private Button closeBtn; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.music_receiver); playBtn = (Button) findViewById(R.id.play); stopBtn = (Button) findViewById(R.id.stop); pauseBtn = (Button) findViewById(R.id.pause); exitBtn = (Button) findViewById(R.id.exit); closeBtn = (Button) findViewById(R.id.close); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); closeBtn.setOnClickListener(this); } @Override public void onClick(View v) { int op = -1; intent = new Intent("com.musicReceiver"); switch (v.getId()) { case R.id.play: op = 1; break; case R.id.stop: // stop music op = 2; break; case R.id.pause: op = 3; break; case R.id.close: this.finish(); break; case R.id.exit: // process by MusicReceiver op = 4; this.finish(); break; } Bundle bundle = new Bundle(); bundle.putInt("op", op); intent.putExtras(bundle); sendBroadcast(intent); } @Override public void onDestroy() { super.onDestroy(); if (intent != null) { stopService(intent); } } }
public class MusicReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Intent it = new Intent(context,MusicService.class); it.putExtras(bundle); if(bundle!=null){ int op = bundle.getInt("op"); if (op == 4) { context.stopService(it); }else{ context.startService(it); } } } }
第三种是bindService(intent, sc, BIND_AUTO_CREATE);来启动service
public class PlayBindMusic extends Activity implements OnClickListener{ private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private BindMusicService musicService; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.bind_music_service); playBtn = (Button) findViewById(R.id.play); stopBtn = (Button) findViewById(R.id.stop); pauseBtn = (Button) findViewById(R.id.pause); exitBtn = (Button) findViewById(R.id.exit); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); connect(); } private void connect() { Intent intent=new Intent("com.bindService"); bindService(intent, sc, BIND_AUTO_CREATE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: musicService.play(); break; case R.id.stop: if (musicService != null) { musicService.stop(); } break; case R.id.pause: if (musicService != null) { musicService.pause(); } break; case R.id.exit: this.finish(); break; } } ServiceConnection sc=new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName arg0) { musicService=null; } @Override public void onServiceConnected(ComponentName arg0, IBinder bind) { musicService= ((BindMusicService.MyBind) bind).getService(); musicService.play(); } }; @Override public void onDestroy(){ super.onDestroy(); if(sc != null){ unbindService(sc); } } }
public class BindMusicService extends Service{ private MediaPlayer mediaPlayer; private final IBinder binder=new MyBind(); @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return binder; } class MyBind extends Binder{ BindMusicService getService(){ return BindMusicService.this; } } @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "show media player", Toast.LENGTH_SHORT).show(); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT).show(); if(mediaPlayer != null){ mediaPlayer.stop(); mediaPlayer.release(); } } public void play() { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.tmp); mediaPlayer.setLooping(false); } if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } } public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } public void stop() { if (mediaPlayer != null) { mediaPlayer.stop(); try { mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数 } catch (IOException ex) { ex.printStackTrace(); } } } }
先定义一个aidl文件
package com.example.myservicetest.remote; interface IMusicControlService{ void play(); void stop(); void pause(); }
public class PlayRemoteMusic extends Activity implements OnClickListener { private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private IMusicControlService musicService; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.remote_music_service); playBtn = (Button) findViewById(R.id.play); stopBtn = (Button) findViewById(R.id.stop); pauseBtn = (Button) findViewById(R.id.pause); exitBtn = (Button) findViewById(R.id.exit); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); connection(); } private void connection() { Intent intent = new Intent("com.remoteMusicReceiver"); bindService(intent, sc, Context.BIND_AUTO_CREATE); } @Override public void onClick(View v) { try { switch (v.getId()) { case R.id.play: musicService.play(); break; case R.id.stop: if (musicService != null) { musicService.stop(); } break; case R.id.pause: if (musicService != null) { musicService.pause(); } break; case R.id.exit: this.finish(); break; } } catch (RemoteException e) { e.printStackTrace(); } } ServiceConnection sc = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { musicService = IMusicControlService.Stub.asInterface(service); } }; @Override public void onDestroy() { super.onDestroy(); if (sc != null) { unbindService(sc); // unBindService } } }
public class RemoteMusicService extends Service { private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return binder; } private final IMusicControlService.Stub binder = new IMusicControlService.Stub() { @Override public void play() throws RemoteException { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(RemoteMusicService.this, R.raw.tmp); mediaPlayer.setLooping(false); } if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } } @Override public void pause() throws RemoteException { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } @Override public void stop() throws RemoteException { if (mediaPlayer != null) { mediaPlayer.stop(); try { mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数 } catch (IOException ex) { ex.printStackTrace(); } } } }; @Override public void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } } }
源码下载 http://download.csdn.net/detail/a79412906/5891027