在写一个程序时遇到了一些情况,我需要使用Service播放音乐,且Activity会进行切换,切换时音乐不能中断。
其中的MediaPlayer创建时如采用MediaPlayer.create(getApplicationContext(),R.raw.XXX)会造成环境为空指针的异常,原因时getApplicationContext()获取到的Service环境为空。
我对此提出的应对方案是在Activity绑定服务时(bindService)向服务传入有效上下文环境信息;服务在收到了有效环境信息后进行MediaPlayer的创建。
请注意本例中有不建议的方法,
Service建议将内容代码添加在重写的onCreate()方法中,不建议添加在构造函数中。
1.Service代码如下(省略使用Binder控制Service的部分)
public class MyService extends Service {
MediaPlayer mediaPlayer;
Context context;
public MyService() {
if(mediaPlayer==null){
while (true){
if(context!=null){//判断环境是否已传入,传入成功后再创建MediaPlayer
mediaPlayer=MediaPlayer.create(context.getApplicationContext(),R.raw.callofsilencexzeroeclipse);
break;
}
Thread.sleep(40);//环境依然为空,40毫秒后再次查看环境情况
}
}
}
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder{
public void musicPause(){
needPause=true;
}
public void musicContinue(){
needPause=false;
}
public void putContext(Context con){
context=con;
}
}
}
2.Activity代码
要记得页面销毁时解绑服务
public class MainActivity extends AppCompatActivity {
private MyService.MyBinder myBinder;
private MyConnection myConnection;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_producer);
//绑定服务
Intent intent=new Intent(ProducerActivity.this,MyService_music.class);
myConnection=new MyConnection();
bindService(intent,myConnection,BIND_AUTO_CREATE);
}
protected void onDestroy() {
unbindService(myConnection);
super.onDestroy();
}
private class MyConnection implements ServiceConnection {
//绑定执行
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myBinder= (MyService_music.MyBinder) iBinder;
myBinder.putContext(MainActivity.this);
}
//接触绑定执行
public void onServiceDisconnected(ComponentName componentName) {
myBinder=null;
}
}
}