android实现一个具有音乐下载到本地功能的代码和布局文件
时间: 2024-02-26 09:56:06 浏览: 140
简单实现Android本地音乐播放器
以下是一个基本的实现音乐下载到本地的代码和布局文件:
布局文件(music_download.xml):
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download Music"
android:layout_centerInParent="true"/>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_download"
android:visibility="gone"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
```
代码(MusicDownloadActivity.java):
```java
public class MusicDownloadActivity extends AppCompatActivity {
private Button btnDownload;
private ProgressBar progressBar;
private String musicUrl = "http://www.example.com/music.mp3";
private String musicName = "music.mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music_download);
btnDownload = findViewById(R.id.btn_download);
progressBar = findViewById(R.id.progress_bar);
btnDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downloadMusic();
}
});
}
private void downloadMusic() {
progressBar.setVisibility(View.VISIBLE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(musicUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle(musicName);
request.setDescription("Downloading music file...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, musicName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading started...", Toast.LENGTH_SHORT).show();
}
}
```
这个例子中,我们使用了Android的DownloadManager类来实现音乐下载到本地的功能。当用户点击“Download Music”按钮时,我们创建了一个DownloadManager请求,并将其加入到DownloadManager队列中以下载音乐文件。同时,我们使用ProgressBar来显示下载进度。
阅读全文