Service的介绍
应用的一部分,与应用执行在同一进程中,生命周期较长,没有可视化界面,运行在后台的一种服务。
Service的两种启动模式
标准启动模式:startService
绑定模式:bindService
两种启动模式的生命周期是不一样的,如下图所示:
Android播发音乐功能案例
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
MusicConnection connection;
MusicService.MyBinder binder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection = new MusicConnection();
Intent musicService = new Intent(this,MusicService.class);
bindService(musicService,connection,BIND_AUTO_CREATE);
}
class MusicConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MusicService.MyBinder)service;//这里获取MusicService传回来的Binder对象
Log.i("Main","已连接");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("Main","连接断开");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//在Activity销毁时手动解绑Service
unbindService(connection);
}
public void onClick(View v){
switch (v.getId()) {
case R.id.start:
binder.play();
break;
case R.id.pause:
binder.pause();
break;
case R.id.stop:
binder.stop();
break;
}
}
}
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class MusicService extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
mediaPlayer = MediaPlayer.create(this,R.raw.zszy);
return new MyBinder();//返回一个Binder对象与Service建立连接
}
class MyBinder extends Binder {
public void play(){
mediaPlayer.start();
Log.i("MusicService","play。。。。。");
}
public void pause(){
mediaPlayer.pause();
Log.i("MusicService","pause。。。。。");
}
public void stop(){
mediaPlayer.stop();
mediaPlayer.prepareAsync();//不加上这个的话stop之后无法重新播放了
Log.i("MusicService","stop。。。。。");
}
}
}
项目源码附件:
https://download.csdn.net/download/qq_34368334/12540360
超链接可能会失效,可以打开我的博客查看我上传的资源哦!
.