Notificaton+IntentService下载下载音乐
思路
1.后台下载用IntentService
2.获得文件总长度
3.每隔多长时间发送通知
详细代码
Service.java
public class DownLoadMusicService extends IntentService {
public InputStream inputStream;
public int total;
public NotificationManager manager;
public int notificaton_id = 100;
public NotificationCompat.Builder builder;
public Handler handler = new Handler();
public int currentProgress = 0;
HttpURLConnection connection;
public DownLoadMusicService() {
super("LoadMusic");
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
initNotification();
startForeground(notificaton_id, builder.build());
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent( @Nullable Intent intent) {
String path = intent.getStringExtra("url");
try {
URL url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
total = connection.getContentLength();
if(connection.getResponseCode() == 200){
handler.post(nThread);
inputStream = connection.getInputStream();
int len = 0;
byte[] bytes = new byte[60];
File file0 = Environment.getExternalStorageDirectory();
File newFile = new File(file0,"dabeizhou.mp3");
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
while ((len = inputStream.read(bytes)) != -1){
currentProgress+=len;
fileOutputStream.write(bytes,0,len);
}
Log.d("amy",currentProgress+"--");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if(connection != null)
connection.disconnect();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void initNotification(){
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("channel_1","name",NotificationManager.IMPORTANCE_LOW);
manager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(this,"channel_1")
.setSmallIcon(R.mipmap.bq1)
.setContentText("下载文件")
.setContentText("下载中。。");
}
Thread nThread = new Thread(){
@Override
public void run() {
super.run();
builder.setProgress(total,currentProgress,false);
manager.notify(notificaton_id,builder.build());
handler.postDelayed(nThread,1000);
}
};
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(nThread);
}
}
Activity.java
public void downloadMusic(View view) {
Intent intent = new Intent(this,DownLoadMusicService.class);
intent.putExtra("url","http://m10.music.126.net/20200704095418/39a88357cd32cb186ccaed3699cd2083/ymusic/8481/cbba/7868/c96fe64c4a34c2137ce30e5f941b145c.mp3");
startService(intent);
}