关于Service必须要知道的:
Service没有可视化界面,是一个后台运行的组件,用来执行不需要与用户交互的任务。服务的两种状态:
Started: 如果Service通过startService()来启动服务,则服务会进入Started状态,一旦服务启动后,可以在后台无限期运行,和启动服务的应用没有了直接关系。
Bound:当应用通过bindService()绑定服务,则服务进入Bound状态。Bound状态的服务会提供一个借口来允许组件与服务进行交互。
两种不同启动方式的服务的生命周期,图片来自Android官网:
左面为通过startService创建服务生命周期,右图为bindServiece创建服务的生命周期。
下面开始创建简单的音乐播放服务:
简单的布局,代码就不贴了:
然后在res目录下新建一个raw目录,随便把一个音乐文件复制进去:
创建一个自定义服务类,继承Service,重写它的onCreate,onStart,onDestroy,onBind,和onUnbind方法:
/** * Created by Administrator on 2017/5/8 0008. */ public class MusicService extends Service { MediaPlayer mediaPlayer; @Nullable @Override public IBinder onBind(Intent intent) { Log.e("Music","onBind"); mediaPlayer.start(); return null; } @Override public void onCreate() { Log.e("Music","onCreate"); mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.beijiaerhupan); mediaPlayer.setLooping(true); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e("Music","onStart"); mediaPlayer.start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.e("Music","onDestroy"); mediaPlayer.stop(); super.onDestroy(); } @Override public boolean onUnbind(Intent intent) { Log.e("Music","onUnBind"); mediaPlayer.stop(); return super.onUnbind(intent); } }在各个方法里打印日志以便观察。其中onStart方法已经弃用,我们重写了它的onStartCommand方法。
在MainActivity中,写下以下代码:
public class MainActivity extends AppCompatActivity { Intent intent; ServiceConnection conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this,MusicService.class); //服务连接对象 conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.e("MainActivity","connected"); } @Override public void onServiceDisconnected(ComponentName name) { Log.e("MainActivity","disconnected"); } }; } public void startMusic(View v){ startService(intent); } public void stopMusic(View v){ stopService(intent); } public void bindMusic(View v){ bindService(intent,conn, Context.BIND_AUTO_CREATE); } public void unbindMusic(View v){ unbindService(conn); }
最后记得要在清单文件中注册!
<service android:name=".MusicService"/>
然后我们点击“开启播放服务”,然后再把应用销毁,日志:
当应用终止以后,其实又重新的调用了一遍onCreate和onStart,然后音乐一直不停地播放下去了。
当点击“绑定服务”,然后点击“解除绑定服务”时,日志:
点击“绑定服务”,然后销毁应用程序:
这里跟网上有些出入,虽然应用退出以后音乐也不在播放,但是Service并没有调用unbind和destroy方法。
不过后来发现,没有调用unbind和destroy是因为我把程序强行销毁了,并没有点后退键退出。又用后退键退出应用,则会正常调用unbind和ondestroy方法