安卓如何向服务传递uri?
我想做个程序,可以动态改变背景音乐,但是传递uri后程序崩溃了。这是服务:publicclassPlayServiceextendsService{privateMedi...
我想做个程序,可以动态改变背景音乐,但是传递uri后程序崩溃了。
这是服务:
public class PlayService extends Service{
private MediaPlayer mediaPlayer;
private boolean isPlaying;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.music);
mediaPlayer.setLooping(false); }
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(intent != null){
Bundle bundle = intent.getExtras();
String path = bundle.getString("url");
try{
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
}catch(IOException e){
e.printStackTrace();
}
}
isPlaying = intent.getBooleanExtra("isPlaying", false);
if (isPlaying){
mediaPlayer.start();
}else {
mediaPlayer.pause();
}
return super.onStartCommand(intent, flags, startId);
}
}
这是要传递的uri:
Bundle mBundle = new Bundle();
notificationStr = pickedUri.toString();
mBundle.putString("url", notificationStr);
Intent i = new Intent(SoundSettingMainActivity.this,PlayService.class);
i.putExtras(mBundle);
startService(i); 展开
这是服务:
public class PlayService extends Service{
private MediaPlayer mediaPlayer;
private boolean isPlaying;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.music);
mediaPlayer.setLooping(false); }
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(intent != null){
Bundle bundle = intent.getExtras();
String path = bundle.getString("url");
try{
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
}catch(IOException e){
e.printStackTrace();
}
}
isPlaying = intent.getBooleanExtra("isPlaying", false);
if (isPlaying){
mediaPlayer.start();
}else {
mediaPlayer.pause();
}
return super.onStartCommand(intent, flags, startId);
}
}
这是要传递的uri:
Bundle mBundle = new Bundle();
notificationStr = pickedUri.toString();
mBundle.putString("url", notificationStr);
Intent i = new Intent(SoundSettingMainActivity.this,PlayService.class);
i.putExtras(mBundle);
startService(i); 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询