我创建了一个应用程序,现在希望它能够连接到手机上的MediaPlayer
,然后从那里播放歌曲,而无需离开我的应用程序。
我想添加一个切换按钮,当打开时,它将开始播放手机上的播放列表。
这是我的代码:
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 :(得分: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();
}
}
}