Service 服务:Android的四大组件之一
主要用于在后台执行一些耗时的操作如下载音乐的播放等
使用其必须在清单文件中注册
其生命周期:
Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法
有两种启动方法 onStart(),onBind();
onStart():这种Service通过调用startService()方法启动,一旦启动,调用者和服务之间没有任何关系,即使调用者不存在了,服务仍然会执行
onBind():这种Service通过调用bindService启动,这种Service可以和调用者进行交互,一旦调用者调用unbindService,那么该服务就会停止
实现方式:
在onDestory()中要解除绑定 unbindService(conn);
参数是ServiceConnection类型的接口
public IBinder onBind(Intent intent)会返回一个IBinder的对象
这样我们就需要在创建这个服务的时候自定义一个类来实现这个接口
在activity中 通过bindService方法绑定服务的时候里面有三个参数
----------- intent对象conntion接口;常量自动创建
bindService(service, conn, BIND_AUTO_CREATE);
在conn接口中拿到service中的binder 通过这个binder调用
重写的方法中在onServiceConnected()方法中拿到
在服务中写好的方法
具体的代码如下
Activity中
public class MainActivity extends Activity {
public Intent service;
public MusicBinder binder;
public NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
service=new Intent(this, MyMusicService.class);
bindService(service, conn, BIND_AUTO_CREATE);
//bindService(service, conn, flags)
showNotification();
}
ServiceConnection conn =new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder=(MusicBinder) service;
}
};
public void click1(View view) {
if(binder!=null){
binder.MusicStart();
}
}
public void click2(View view) {
if(binder!=null){
binder.musicStop();
}
}
public void click3(View view) {
if(binder!=null){
binder.Musicpause();
}
}
public void click4(View view) {
if(binder!=null){
binder.musicStop();
}
stopService(service);
finish();
}
public void showNotification(){
manager=(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
//创建通知
Notification notification=new Notification(R.drawable.ic_launcher, "音乐播放", System.currentTimeMillis());
// //设置提示音
// notification.defaults(de)
//设置是否消除
notification.flags|=Notification.FLAG_ONGOING_EVENT;//必须自己消除
//设置布局
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.notification);
//设置开始按钮的监听
PendingIntent intent=PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.music.play"), 0);
remoteViews.setOnClickPendingIntent(R.id.bu1, intent);
//设置暂停
PendingIntent intent_pause=PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.music.pause"), 0);
remoteViews.setOnClickPendingIntent(R.id.bu2, intent_pause);
//设置退出
PendingIntent intent_exit=PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.music.exit"), 0);
//将remoteVIew设置给notification
notification.contentView=remoteViews;
//给notiffication设置意图
Intent intent_noti=new Intent(getApplicationContext(),MainActivity.class);
//设置启动模式
intent_noti.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pending=PendingIntent.getActivity(getApplicationContext(), 0, intent_noti, 0);
notification.contentIntent=pending;
manager.notify(1, notification);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("Service", "onDestroy=========================================");
manager.cancelAll();
unbindService(conn);//解除绑定
}
}
Service中
public class MyMusicService extends Service {
public MediaPlayer mediaPlayer;
public static MusicBinder binder ;
@Override
public IBinder onBind(Intent intent) {
binder= new MusicBinder();
return binder;
}
public class MusicBinder extends Binder {
public void MusicStart() {
if (mediaPlayer != null) {
mediaPlayer.start();
Log.i("Service",mediaPlayer.toString()+"-----------------------" );
}
}
public void musicStop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
public void Musicpause() {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
}
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.start);
Log.i("Service", " onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.release();
mediaPlayer = null;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
public static class reciver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.music.play")){
binder.MusicStart();
}else if(intent.getAction().equals("com.music.pause")){
binder.Musicpause();
}else if(intent.getAction().equals("com.music.exit")){
binder.musicStop();
}
}
}
}