我有一个应用程序,我想从SD卡中选择一首歌并使用按钮播放它。但是,所选歌曲的路径不会返回onActivityResult()。它始终显示为null。我怎么能得到它?任何帮助表示赞赏。
这是我的作品
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
buttonChoose.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.buttonChoose) {
System.gc();
Intent intent = new Intent(android.content.Intent.ACTION_GET_CONTENT);
Uri data = Uri.parse("file:///sdcard/media/audio/notifications");
String type = "audio/mp3";
intent.setDataAndType(data, type);
startActivityForResult(intent, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (data != null) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
uri = getIntent().getData();
if (uri != null) {
mp.setDataSource(getApplicationContext(), uri);
mp.prepare();
mp.start();
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} else {
Toast.makeText(MainActivity.this, "Data is null...", Toast.LENGTH_SHORT).show();
}
} catch (Exception exception) {
exception.printStackTrace();
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
}
答案 0 :(得分:1)
在onActivityResult而不是uri = data.getData();
uri = getIntent().getData();
答案 1 :(得分:0)
检查AndroidManifest.xml中的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />