2014-04-23 118 views
0

我已经创建了一个应用程序,现在希望它能够连接到手机上的MediaPlayer,并从那里播放歌曲,无需离开我的应用程序。如何让我的Android应用程序从手机的音乐播放器播放音乐?

我想添加一个切换按钮,当打开时,它将开始播放手机上的播放列表。

这是我的代码:

public class MainActivity extends Activity implements OnClickListener{ 
     ToggleButton tbMusic; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tbMusic=(ToggleButton) findViewById(R.id.tbMusic); 
     if(tbMusic.isChecked()) 
     { 
      //here i want the command to be start playing the music 
     } 
     tbMusic.setOnClickListener(this); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.property, menu); 
     return true; 
    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     if(v.getId()==R.id.tbMusic) 
     { 
      if(tbMusic.isChecked()) 
      { 
       //here i want the command to be start playing the music 
      } 
      else 
      { 
       //here i want a command that will stop the media player. 
      } 
     } 
    } 

回答

0
Private MediaPalyer mp; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mp = MediaPlayer.create(this,R.raw.mymusic); 

    tbMusic=(ToggleButton) findViewById(R.id.tbMusic); 
    if(tbMusic.isChecked()) 
    { 
     mp.start(); 
    } 
    tbMusic.setOnClickListener(this); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.property, menu); 
    return true; 
} 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    if(v.getId()==R.id.tbMusic) 
    { 
     if(tbMusic.isChecked()) 
     { 
      mp.start(); 
     } 
     else 
     { 
      mp.pause(); 
     } 
    } 
}