我曾使用下载管理器下载mp3
文件,但我还希望能够在activity
中播放从我的应用程序下载的文件,但我不能这样做。以下是我用于从服务器下载文件的代码:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("https://eplayer.000webhostapp.com/Sleep%20Away.mp3"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
public void audioPlayer(String path, String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
}
尝试播放已下载的mp3的代码:
public void audioPlayer(String path, String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource( ACTION_DOWNLOAD_COMPLETE + File.separator +"Sleep Away");
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}