2016-12-22 4 views
0

AndroidアプリでMediaPlayerオブジェクトを再利用する方法を知りたいので、アプリ内で他のアクティビティを行っても現在の再生は停止しません。例えば、私は現在、AlarmManager受信(BroadcastReceiver)を行うクラスの中でMediaPlayerを使用しています。ここに私が持っているものがあります、これを行うより良い方法がありますか?効果的にAndroid Media Playerを再利用する

public class MyBroadcastReceiver extends BroadcastReceiver 
{ 
    MediaPlayer mp; 


@Override 
public void onReceive(Context context, Intent intent) 
{ 
    // TODO Auto-generated method stub 
    mp = new MediaPlayer(); 
    playSound(context); 
} 
private void playSound(Context ctx) 
{ 
    //play the notification sound 
    AssetFileDescriptor afd = null; 
    try 
    { 
     afd = ctx.getAssets().openFd("notify.mp3"); 
    } 
    catch (IOException e1) 
    { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    mp.setVolume(5f, 5f); 
    try 
    { 
     mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); 
    } 
    catch (IllegalArgumentException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (IllegalStateException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    try 
    { 
     mp.prepare(); 
    } 
    catch (IllegalStateException | IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    mp.start(); 
    if(!mp.isPlaying()) 
    { 
     mp.release(); 
    } 
} 
} 
+1

[関連](http://stackoverflow.com/questions/29371136/how-to-make-my-mediaplayer-activity-run-in-background) –

答えて

関連する問題