首先我创建了一个名为GetMusics.java
的类,所以我希望将音乐名称路径转换为MusicPlater.java
类,但onActivityResult
方法不起作用。我不知道我在哪里犯错误。
这是GetMusic.java
类
public class GetMusics extends ListActivity{
private final String SD_PATH = Environment.getExternalStorageDirectory().getPath();
List<String> songs = new ArrayList<String>();
MediaPlayer mp = new MediaPlayer();
class Mp3Filter implements FilenameFilter{
@Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return filename.endsWith(".mp3");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.music_layout);
updateMusicList();
}
private void updateMusicList(){
File file = new File(SD_PATH);
if(file.listFiles(new Mp3Filter()).length>0){
for(File f : file.listFiles(new Mp3Filter()) ){
songs.add(f.getName());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
songs);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent i = new Intent(GetMusics.this,MusicPlayer.class);
i.putExtra("song_name", songs.get(position));
setResult(100,i);
finish();
}
}
这是MusicPlayer.java类
public class MusicPlayer extends Activity {
MediaPlayer mp = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.music_player);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==100){
String song_name = data.getStringExtra("song_name");
mp.reset();
try {
mp.setDataSource(Environment.getExternalStorageDirectory()
.getPath() + "/" + song_name);
mp.prepare();
mp.start();
} 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();
}
}
}
}