1. startService?
1.1Activity
调用startServise和stopService即可
final Intent intent = new Intent(MainActivity.this,StartService.class);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(intent);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(intent);
}
});
1.2Service
service的生命周期如下:onCreate----》onStartCommand------》onDestroy
onCreate方法只调用一次? ?onStartCommand方法会调用多次
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG,"onCreate");
mediaPlayer = MediaPlayer.create(this,R.raw.music);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"onStartCommand");
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
else {
mediaPlayer.start();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG,"onDestroy");
mediaPlayer.release();
super.onDestroy();
}
2.bindService
2.1Activity里面
定义ServiceConnection??
onServiceConnected在onBind时调用
onServiceDisconnected在正常情况下是不被调用的,它的调用时机是当Service服务被异外销毁时,例如内存的资源不足时这个方法才被自动调用。
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.e(getClass().getName(),"onServiceConnected");
myBinder = (BindService.MyBinder) iBinder;
myBinder.startMusic();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.e(getClass().getName(),"onServiceDisconnected");
}
};
final Intent intent1 = new Intent(MainActivity.this,BindService.class);
bind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bindService(intent1,serviceConnection,BIND_AUTO_CREATE);
}
});
unbind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
unbindService(serviceConnection);
}
});
2.2Service
service的生命周期如下? onCreate----》onBind-----》onUnbind-----》onDestroy
MyBinder myBinder = new MyBinder();
MediaPlayer mediaPlayer;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
Log.e(TAG,"onBind");
return myBinder;
}
@Override
public void onCreate() {
Log.e(TAG,"onCreate");
mediaPlayer = MediaPlayer.create(this,R.raw.music);
super.onCreate();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG,"onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.e(TAG,"onDestroy");
mediaPlayer.release();
super.onDestroy();
}
class MyBinder extends Binder{
public void startMusic(){
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
}
}
public void stopMusic(){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
}
}
|